For this, use findOneAndUpdate() in MongoDB. The findOneAndUpdate() method updates a single document based on the filter and sort criteria.
Let us create a collection with documents −
> db.demo553.insertOne( ... { ... id:101, ... "Name":"John", ... midExamDetails: ... [ ... {"SubjectName":"MySQL","Marks":70}, ... {"SubjectName":"MongoDB","Marks":35} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e8e3da19e5f92834d7f05ed") }
Display all documents from a collection with the help of find() method −
> db.demo553.find();
This will produce the following output −
{ "_id" : ObjectId("5e8e3da19e5f92834d7f05ed"), "id" : 101, "Name" : "John", "midExamDetails" : [ { "SubjectName" : "MySQL", "Marks" : 70 }, { "SubjectName" : "MongoDB", "Marks" : 35 } ] }
Following is the query to the syntax for updating an object inside an array within a MongoDB document −
> db.demo553.findOneAndUpdate( ... { id:101, ... "midExamDetails.SubjectName":"MongoDB" ... }, ... { $set:{ ... 'midExamDetails.$.Marks': 97 ... } ... } ... ); { "_id" : ObjectId("5e8e3da19e5f92834d7f05ed"), "id" : 101, "Name" : "John", "midExamDetails" : [ { "SubjectName" : "MySQL", "Marks" : 70 }, { "SubjectName" : "MongoDB", "Marks" : 35 } ] }
Display all documents from a collection with the help of find() method −
> db.demo553.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e8e3da19e5f92834d7f05ed"), "id" : 101, "Name" : "John", "midExamDetails" : [ { "SubjectName" : "MySQL", "Marks" : 70 }, { "SubjectName" : "MongoDB", "Marks" : 97 } ] }