To update the inner field, use the below syntax −
db.yourCollectionName.update({"_id" : yourObjectId}, {$set : {"yourOuterFieldName.yourInnerFieldName" :yourValue}});
Let us first create a collection with documents −
> db.updateDocumentDemo.insertOne( ... { ... ... "StudentDetails" : { ... "StudentFirstName" : "Adam", ... "StudentLastName" : "Samith" ... }, ... "StudentOtherDetails" : { ... "StudentFavouriteSubject" : "MySQL", ... "StudentScore" : 45 ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd50bb32cba06f46efe9efe") }
Following is the query to display all documents from a collection with the help of find() method −
> db.updateDocumentDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd50bb32cba06f46efe9efe"), "StudentDetails" : { "StudentFirstName" : "Adam", "StudentLastName" : "Samith" }, "StudentOtherDetails" : { "StudentFavouriteSubject" : "MySQL", "StudentScore" : 45 } }
Following is the query to update the document in MongoDB −
> db.updateDocumentDemo.update({"_id" : ObjectId("5cd50bb32cba06f46efe9efe")}, ... {$set : {"StudentOtherDetails.StudentFavouriteSubject" :"MongoDB"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us display the documents once again −
> db.updateDocumentDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd50bb32cba06f46efe9efe"), "StudentDetails" : { "StudentFirstName" : "Adam", "StudentLastName" : "Samith" }, "StudentOtherDetails" : { "StudentFavouriteSubject" : "MongoDB", "StudentScore" : 45 } }