To update child objects, use $set operator. Let us first create a collection with document −
>db.updateChildObjectsDemo.insertOne({"StudentName":"Chris","StudentOtherDetails":{"StudentSubject":"MongoDB","StudentCountryName":"AUS"}}); { "acknowledged" : true, "insertedId" : ObjectId("5ce964e078f00858fb12e91f") }
Following is the query to display all documents from a collection with the help of find() method −
> db.updateChildObjectsDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5ce964e078f00858fb12e91f"), "StudentName" : "Chris", "StudentOtherDetails" : { "StudentSubject" : "MongoDB", "StudentCountryName" : "AUS" } }
Following is the query to update child objects in MongoDB −
> db.updateChildObjectsDemo.update({"StudentName" : "Chris"},{$set:{"StudentOtherDetails.StudentCountryName":"UK"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check the document once again −
> db.updateChildObjectsDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5ce964e078f00858fb12e91f"), "StudentName" : "Chris", "StudentOtherDetails" : { "StudentSubject" : "MongoDB", "StudentCountryName" : "UK" } }