MongoDB query to update an array element matching a condition using $push?


Let us first create a collection with documents −

> db.updateArrayElementDemo.insertOne(
   {
      "UserDetails":
      [
         {
            "UserName":"Chris",
            "UserAge":23
         }
      ]
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce9029378f00858fb12e90d")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5ce9029378f00858fb12e90d"),
   "UserDetails" : [
      {
         "UserName" : "Chris",
         "UserAge" : 23
      }
   ]
}

Following is the query to update an array element matching a condition using $push −

db.updateArrayElementDemo.update(
   {"UserDetails.UserAge": 23},
   {"$push": {"UserDetails.$.UserCountryName": "US"}}
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us check the document once again −

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

This will produce the following output −

{
   "_id" : ObjectId("5ce9029378f00858fb12e90d"),
   "UserDetails" : [
      {
         "UserName" : "Chris",
         "UserAge" : 23,
         "UserCountryName" : [
            "US"
         ]
      }
   ]
}

Updated on: 30-Jul-2019

326 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements