To update or modify the existing documents of a collection in MongoDB, you need to use update() method. The syntax is as follows:
db.yourCollectionName.update(yourExistingValue, yourUpdatedValue);
Here, we will create a collection with name updateinformation. The query to create a collection is as follows. MongoDB creates a collection automatically when you insert some document using insert() method as shown below:
> db.updateInformation.insert({"StudentName":"Larry",StudentAge:35,StudentMarks:89});
The following is the output:
WriteResult({ "nInserted" : 1 })
Now you can display the documents with the help of find() method from the collection updateinformation. The query is as follows:
> db.updateInformation.find();
The following is the output displaying the documents in the collection we added above:
{ "_id" : ObjectId("5c6aa29a64f3d70fcc9147f7"), "StudentName" : "Larry", "StudentAge" : 35, "StudentMarks" : 89 }
Now, let us update or modify the existing documents ‘StudentAge’ 35 to 24. For this, we will use the update() method. The query is as follows:
> db.updateInformation.update({StudentAge:35},{$set:{StudentAge:24}});
The following is the output:
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
We have updated the StudentAge 35 to 24 above. Let us check the document once again. The query is as follows:
> db.updateInformation.find().pretty();
The following is the output:
{ "_id" : ObjectId("5c6aa29a64f3d70fcc9147f7"), "StudentName" : "Larry", "StudentAge" : 24, "StudentMarks" : 89 }
Look at the StudentAge field above. The age is now updated to 24/ Previously, it was 35.