Update an array element matching a condition using $push in MongoDB


For this, use update command and $push. Let us first create a collection with documents −

>db.demo9.insertOne({"StudentDetails":[{"StudentName":"Chris","ListOfSubject":["MySQL","Java"]}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e0f6438d7df943a7cec4f94")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5e0f6438d7df943a7cec4f94"),
   "StudentDetails" : [
      {
         "StudentName" : "Chris",
         "ListOfSubject" : [
            "MySQL",
            "Java"
         ]
      }
   ]
}

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

> db.demo9.update( { "StudentDetails.StudentName":"Chris"}, {$push:{"StudentDetails.$.ListOfSubject":"MongoDB"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

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

This will produce the following output −

{
   "_id" : ObjectId("5e0f6438d7df943a7cec4f94"),
   "StudentDetails" : [
      {
         "StudentName" : "Chris",
         "ListOfSubject" : [
            "MySQL",
            "Java",
            "MongoDB"
         ]
      }
   ]
}

Updated on: 01-Apr-2020

459 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements