MongoDB $addToSet to add a deep nested array of object?

MongoDBDatabaseBig Data Analytics

The $addToSet operator adds a value to an array unless the value is already present, in which case $addToSet does nothing to that array.

Let us first create a collection with documents −

> db.demo380.insertOne({
...
...    "details" : [
...       {
...          "Name" : "Chris",
...          "details1" : [ ]
...       },
...       {
...          "Name" : "David",
...          "details1" : [ ]
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5b56e32ae06a1609a00b11")
}

Display all documents from a collection with the help of find() method −

> db.demo380.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e5b56e32ae06a1609a00b11"),
   "details" : [
      {
         "Name" : "Chris",
         "details1" : [ ]
      },
      {
         "Name" : "David",
         "details1" : [ ]
      }
   ]
}

Following is the query to add a deep nested array of object −

> db.demo380.update({
...    "details.Name": "David"
...    }, {
...    $addToSet: {
...       "details.$.details1": {
...          'SubjectName': "MongoDB",
...          'TeacherName':"Bob"
...       }
...    }
... }, false, true);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Display all documents from a collection with the help of find() method −

> db.demo380.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e5b56e32ae06a1609a00b11"),
   "details" : [
      {
         "Name" : "Chris",
         "details1" : [ ]
      },
      {
         "Name" : "David",
         "details1" : [
            {
               "SubjectName" : "MongoDB",
               "TeacherName" : "Bob"
            }
         ]
      }
   ]
}
raja
Published on 02-Apr-2020 13:31:38
Advertisements