Updating Nested Embedded Documents in MongoDB?


To update bested documents in MongDB, use UPDATE() and positional($) operator. Let us create a collection with documents −

> db.demo643.insertOne({
...    details : [
...       {
...          "CountryName":"US",
...          StudentDetails:[{Name:"Chris"},{SubjectName:"MySQL"}]
...       },
...
...       {
...          "CountryName":"UK",
...          StudentDetails:[{Name:"Bob"},{SubjectName:"Java"}]
...       }
...    ]
... }
... )
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9c737f6c954c74be91e6e3")
}

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

> db.demo643.find();

This will produce the following output −

{ "_id" : ObjectId("5e9c737f6c954c74be91e6e3"), "details" : [ { "CountryName" : "US", "StudentDetails" : [ { "Name" : "Chris" }, { "SubjectName" : "MySQL" } ] }, { "CountryName" : "UK", "StudentDetails" : [ { "Name" : "Bob" }, { "SubjectName" : "Java" } ] } ] }

Following is the query to update nested embedded documents in MongoDB −

> db.demo643.update({"details.CountryName": "UK"}, {"$push": {"details.$.StudentDetails": {Marks:78}}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

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

This will produce the following output −

{
   "_id" : ObjectId("5e9c737f6c954c74be91e6e3"),
   "details" : [
      {
         "CountryName" : "US",
         "StudentDetails" : [
            {
               "Name" : "Chris"
            },
            {
               "SubjectName" : "MySQL"
            }
         ]
      },
      {
         "CountryName" : "UK",
         "StudentDetails" : [
            {
               "Name" : "Bob"
            },
            {
               "SubjectName" : "Java"
            },
            {
               "Marks" : 78
            }
         ]
      }
   ]
}

Updated on: 12-May-2020

824 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements