Update elements inside an array in MongoDB?


To update elements inside an array, use $set in MongoDB. Let us create a collection with documents −

> db.demo494.insertOne(
... {
...
...    "CollegeDetails" : [
...       {
...          "CollegeName" : "MIT",
...          "Fees" : 80000
...       },
...       {
...          "CollegeName" : "SU",
...          "Fees" : 90000
...       }
...    ]
... }
... )
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e84a5c1b0f3fa88e22790c9")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5e84a5c1b0f3fa88e22790c9"),
   "CollegeDetails" : [
      {
         "CollegeName" : "MIT",
         "Fees" : 80000
      },
      {
         "CollegeName" : "SU",
         "Fees" : 90000
      }
   ]
}

Following is the query to update elements inside an array in MongoDB −

> db.demo494.update(
...
... {
...    "CollegeDetails.CollegeName": "MIT"
... },
...
... {
...    $set:
...       {
...          "CollegeDetails.$.Fees" : 100000
...       }
...    }
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

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

This will produce the following output −

{
   "_id" : ObjectId("5e84a5c1b0f3fa88e22790c9"),
   "CollegeDetails" : [
      {
         "CollegeName" : "MIT",
         "Fees" : 100000
      },
      {
         "CollegeName" : "SU",
         "Fees" : 90000
      }
   ]
}

Updated on: 13-May-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements