Implement MongoDB $addToSet for an array in an array and append a value


For this, use update() along with $addToSet. The $addToSet operator adds value to an array unless the value is already present, in which case $addToSet does nothing to that array. Let us create a collection with documents −

> db.demo509.insertOne(
... {
...
...    "value1" : [
...       {
...          "value2" : [
...             76,
...             14,
...             56
...          ]
...       },
...       {
...
...          "value2" : [
...             12,
...             19,
...             91
...          ]
...       },
...       {
...
...          "value2" : [
...             87
...          ]
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e88421d987b6e0e9d18f57d")
}

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

> db.demo509.find();

This will produce the following output −

{ "_id" : ObjectId("5e88421d987b6e0e9d18f57d"), "value1" : [
   { "value2" : [ 76, 14, 56 ] },
   { "value2" : [ 12, 19, 91 ] }, { "value2" : [ 87 ] }
] }

Following is the query to implement $addToSet and append in an array −

> db.demo509.update({},{$addToSet:{"value1.2.value2":1000}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

> db.demo509.find();

This will produce the following output −

{ "_id" : ObjectId("5e88421d987b6e0e9d18f57d"), "value1" : [
   { "value2" : [ 76, 14, 56 ] },
   { "value2" : [ 12, 19, 91 ] }, { "value2" : [ 87, 1000 ] } 
] }

Updated on: 13-May-2020

270 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements