MongoDB query to update all documents matching specific IDs

MongoDBDatabaseBig Data Analytics

Use the updateMany() function to update all documents that match the filter criteria. Let us create a collection with documents −

> db.demo476.insertOne({_id:1,"Name":"Chris"});
{ "acknowledged" : true, "insertedId" : 1 }
> db.demo476.insertOne({_id:2,"Name":"David"});
{ "acknowledged" : true, "insertedId" : 2 }
> db.demo476.insertOne({_id:3,"Name":"Bob"});
{ "acknowledged" : true, "insertedId" : 3 }
> db.demo476.insertOne({_id:4,"Name":"Carol"});
{ "acknowledged" : true, "insertedId" : 4 }

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

> db.demo476.find();

This will produce the following output −

{ "_id" : 1, "Name" : "Chris" }
{ "_id" : 2, "Name" : "David" }
{ "_id" : 3, "Name" : "Bob" }
{ "_id" : 4, "Name" : "Carol" }

Following is the query to update all documents matching specific IDs −

> db.demo476.updateMany({_id:{$in:[1,3]}},{$set:{Name:"Robert"}});
{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }

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

> db.demo476.find();

This will produce the following output −

{ "_id" : 1, "Name" : "Robert" }
{ "_id" : 2, "Name" : "David" }
{ "_id" : 3, "Name" : "Robert" }
{ "_id" : 4, "Name" : "Carol" }
raja
Published on 11-May-2020 13:15:47
Advertisements