Update values in multiple documents with multi parameter in MongoDB?

MongoDBDatabaseBig Data Analytics

You need to set multi to true. Include the option multi − true to update all documents that match the query criteria.

Let us first create a collection with documents −

> db.demo390.insertOne({"FirstName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5d1f3a22064be7ab44e7fa")
}
> db.demo390.insertOne({"FirstName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5d1f3e22064be7ab44e7fb")
}
> db.demo390.insertOne({"FirstName":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5d1f4122064be7ab44e7fc")
}
> db.demo390.insertOne({"FirstName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5d1f4422064be7ab44e7fd")
}

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

> db.demo390.find();

This will produce the following output −

{ "_id" : ObjectId("5e5d1f3a22064be7ab44e7fa"), "FirstName" : "Chris" }
{ "_id" : ObjectId("5e5d1f3e22064be7ab44e7fb"), "FirstName" : "David" }
{ "_id" : ObjectId("5e5d1f4122064be7ab44e7fc"), "FirstName" : "Bob" }
{ "_id" : ObjectId("5e5d1f4422064be7ab44e7fd"), "FirstName" : "Chris" }

Following is the query to update values with multi − true −

> db.demo390.update({FirstName:"Chris"},{$set:{"FirstName":"John"}},{multi:true});
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })

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

> db.demo390.find();

This will produce the following output −

{ "_id" : ObjectId("5e5d1f3a22064be7ab44e7fa"), "FirstName" : "John" }
{ "_id" : ObjectId("5e5d1f3e22064be7ab44e7fb"), "FirstName" : "David" }
{ "_id" : ObjectId("5e5d1f4122064be7ab44e7fc"), "FirstName" : "Bob" }
{ "_id" : ObjectId("5e5d1f4422064be7ab44e7fd"), "FirstName" : "John" }
raja
Published on 02-Apr-2020 14:00:44
Advertisements