Use $addToSet operator to update array element. Let us first create a collection with documents −
> db.updateArrayDemo.insertOne( ... { ... ... "ClientDetails" : [ ... { ... "ClientName" : "John", ... "DeveloperDetails" : [ ] ... }, ... { ... "ClientName" : "Larry", ... "DeveloperDetails" : [ ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5ccf465edceb9a92e6aa1960") }
Following is the query to display all documents from a collection with the help of find() method −
> db.updateArrayDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5ccf465edceb9a92e6aa1960"), "ClientDetails" : [ { "ClientName" : "John", "DeveloperDetails" : [ ] }, { "ClientName" : "Larry", "DeveloperDetails" : [ ] } ] }
Following is the query to update array element −
> db.updateArrayDemo.update({ "ClientDetails.ClientName": "Larry" }, { $addToSet: { "ClientDetails.$.Technology": { 'DeveloperName': "Chris", 'WorkExperience':5 } } }, false, true); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check the array element has been updated or not −
> db.updateArrayDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5ccf465edceb9a92e6aa1960"), "ClientDetails" : [ { "ClientName" : "John", "DeveloperDetails" : [ ] }, { "ClientName" : "Larry", "DeveloperDetails" : [ ], "Technology" : [ { "DeveloperName" : "Chris", "WorkExperience" : 5 } ] } ] }