How to update MongoDB Object?


To update MongoDB object, use UPDATE(). Let us create a collection with documents −

> db.demo77.insertOne({"Details" : { "Score" : 78 } });
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2bd6f371bf0181ecc4228a")
}

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

> db.demo77.find();

This will produce the following output −

{ "_id" : ObjectId("5e2bd6f371bf0181ecc4228a"), "Details" : { "Score" : 78 } }

Following is the query to update MongoDB object −

> db.demo77.update({'Details.Score':78},{$set:{'Details.Score':89}},{multi:true});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

> db.demo77.find();

This will produce the following output −

{ "_id" : ObjectId("5e2bd6f371bf0181ecc4228a"), "Details" : { "Score" : 89 } }

Updated on: 30-Mar-2020

245 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements