MongoDB query to update the nested document?



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       }    } }
Updated on: 2020-05-15T07:59:58+05:30

471 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements