Tutorialspoint

1 Answer
Anvi Jain

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" ] } ] }

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.