MongoDB query to update the nested document?

MongoDBDatabaseBig Data Analytics

To update the nested document, use update() and within that, use dot notation. Let us create a collection with documents −

> db.demo607.insertOne(
...    {
...       id:1,
...       "Info1" : {
...          "Name" : "Chris",
...          "Age" : 21,
...
...          "Info2" : {
...             "SubjectName" : "MongoDB",
...             "Marks" : 89
...          }
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9742a5f57d0dc0b182d62a")
}

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

> db.demo607.find();

This will produce the following output −

{ "_id" : ObjectId("5e9742a5f57d0dc0b182d62a"), "id" : 1, "Info1" :
   { "Name" : "Chris", "Age" : 21, "Info2" : { "SubjectName" : "MongoDB", "Marks" : 89 } } 
}

Following is the query to update nested document −

> db.demo607.update({id:1},{$set:{"Info1.Info2.Marks":90}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

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

This will produce the following output −

{
   "_id" : ObjectId("5e9742a5f57d0dc0b182d62a"),
   "id" : 1,
   "Info1" : {
      "Name" : "Chris",
      "Age" : 21,
      "Info2" : {
         "SubjectName" : "MongoDB",
         "Marks" : 90
      }
   }
}
raja
Published on 15-May-2020 11:28:19
Advertisements