Is it possible to utilize $addToSet multiple times in the same update?


Yes, it is possible using the UPDATE() method. Let us create a collection with documents −

> db.demo27.insertOne({"StudentDetails":{"101":{"Subject":["Java"]}}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e15f9e822d07d3b95082e7f")
}
> db.demo27.insertOne({"StudentDetails":{"101":{"Subject":["MySQL"]}}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e15f9eb22d07d3b95082e80")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5e15f9e822d07d3b95082e7f"),
   "StudentDetails" : {
      "101" : {
         "Subject" : [
            "Java"
         ]
      }
   }
}
{
   "_id" : ObjectId("5e15f9eb22d07d3b95082e80"),
   "StudentDetails" : {
      "101" : {
         "Subject" : [
            "MySQL"
         ]
      }
   }
}

Following is the query to implement $addToSet multiple times in the same update −

> db.demo27.update({}, {$addToSet: {"StudentDetails.101.Subject": "MongoDB"}}, {upsert: true})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

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

This will produce the following output −

{
   "_id" : ObjectId("5e15f9e822d07d3b95082e7f"),
   "StudentDetails" : {
      "101" : {
         "Subject" : [
            "Java",
            "MongoDB"
         ]
      }
   }
}
{
   "_id" : ObjectId("5e15f9eb22d07d3b95082e80"),
   "StudentDetails" : {
      "101" : {
         "Subject" : [
            "MySQL"
         ]
      }
   }
}

Updated on: 02-Apr-2020

182 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements