How to update a MongoDB document without overwriting the existing one?

MongoDBDatabaseBig Data Analytics

To update only a field value, use update() along with $set. This won’t overwrite the existing one. Let us first create a collection with documents −

> db.demo401.insertOne(
...    {
...       "_id" : 1001,
...       "Name" : "Chris",
...       "SubjectName" : "MongoDB",
...       "Score" : 45
...    }
... );
{ "acknowledged" : true, "insertedId" : 1001 }

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

> db.demo401.find();

This will produce the following output −

{ "_id" : 1001, "Name" : "Chris", "SubjectName" : "MongoDB", "Score" : 45 }

Following is the query to update a document without overwriting the existing one −

> db.demo401.update({_id: 1001}, {$set: {Score:89}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

> db.demo401.find();

This will produce the following output −

{ "_id" : 1001, "Name" : "Chris", "SubjectName" : "MongoDB", "Score" : 89 }
raja
Published on 03-Apr-2020 16:11:36
Advertisements