Updating nested document in MongoDB


To update the nested document, use $set. Let us create a collection with documents −

> db.demo315.insertOne({ _id :101,
...  details: [
...     {Name: 'Chris', subjects: [{id:1001, SubjectName:"MySQL"}]}
...  ]
... }
...)
{ "acknowledged" : true, "insertedId" : 101 }

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

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

This will produce the following output −

{
   "_id" : 101,
   "details" : [
      {
         "Name" : "Chris",
         "subjects" : [
            {
               "id" : 1001,
               "SubjectName" : "MySQL"
            }
         ]
      }
   ]
}

Following is the query to update the nested document in MongoDB −

> db.demo315.update ({_id:101}, { '$set': {"details.0.subjects.1.id" :1004} })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

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

This will produce the following output −

{
   "_id" : 101,
   "details" : [
      {
         "Name" : "Chris",
         "subjects" : [
            {
               "id" : 1001,
               "SubjectName" : "MySQL"
            },
            {
               "id" : 1004
            }
         ]
      }
   ]
}

Updated on: 02-Apr-2020

232 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements