How to push new items to an array inside of an object in MongoDB?


You can use $elemMatch operator for this. Let us first create a collection with documents −

> db.pushNewItemsDemo.insertOne(
   {
      "_id" :1,
      "StudentScore" : 56,
      "StudentOtherDetails" : [
         {
            "StudentName" : "John",
            "StudentFriendName" : [
               "Bob",
               "Carol"
            ]
         },
         {
            "StudentName" : "David",
            "StudentFriendName" : [
               "Mike",
               "Sam"
            ]      
         }
      ]
   }
);
{ "acknowledged" : true, "insertedId" : 1 }

Following is the query to display all documents from a collection with the help of find() method −

> db.pushNewItemsDemo.find();

This will produce the following output −

{ "_id" : 1, "StudentScore" : 56, "StudentOtherDetails" : [ { "StudentName" : "John", "StudentFriendName" : [ "Bob", "Carol" ] }, { "StudentName" : "David", "StudentFriendName" : [ "Mike", "Sam" ] } ] }

Following is the query to push new items to an array inside of an object −

>db.pushNewItemsDemo.update({"_id":1,"StudentOtherDetails":{"$elemMatch":{"StudentName":"David"}}},
   {"$push":{"StudentOtherDetails.$.StudentFriendName":"James"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us check the documents once again −

> db.pushNewItemsDemo.find();

This will produce the following output −

{ "_id" : 1, "StudentScore" : 56, "StudentOtherDetails" : [ { "StudentName" : "John", "StudentFriendName" : [ "Bob", "Carol" ] }, { "StudentName" : "David", "StudentFriendName" : [ "Mike", "Sam", "James" ] } ] }

Updated on: 30-Jul-2019

770 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements