How to update many documents with one query in MongoDB?


To update many documents with a single query, use bulkWrite() in MongoDB. Let us create a collection with documents −

> db.demo760.insertOne({id:1,details:{Value1:100,Value2:50}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eb0309f5637cd592b2a4aee")
}
> db.demo760.insertOne({id:2,details:{Value1:60,Value2:70}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eb030a15637cd592b2a4aef")
}
> db.demo760.insertOne({id:3,details:{Value1:80,Value2:90}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eb030a15637cd592b2a4af0")
}

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

> db.demo760.find();

This will produce the following output −

{ "_id" : ObjectId("5eb0309f5637cd592b2a4aee"), "id" : 1, "details" : { "Value1" : 100, "Value2" : 50 } }
{ "_id" : ObjectId("5eb030a15637cd592b2a4aef"), "id" : 2, "details" : { "Value1" : 60, "Value2" : 70 } }
{ "_id" : ObjectId("5eb030a15637cd592b2a4af0"), "id" : 3, "details" : { "Value1" : 80, "Value2" : 90 } }

Following is the query to update many documents with one query in MongoDB −

> db.demo760.bulkWrite([
...    {
...       updateOne: {
...          filter: {id: 1},
...          update: {$set: {'details.Value1': 900, 'details.Value2': 500}},
...       }
...    },
...    {
...    updateOne: {
...       filter: {id: 2},
...       update: {$set: {'details.Value1': 1000, 'details.Value2': 2000}},
...    },
... }
... ])
{
   "acknowledged" : true,
   "deletedCount" : 0,
   "insertedCount" : 0,
   "matchedCount" : 2,
   "upsertedCount" : 0,
   "insertedIds" : {
   },
   "upsertedIds" : {
   }
}

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

> db.demo760.find();

This will produce the following output −

{ "_id" : ObjectId("5eb0309f5637cd592b2a4aee"), "id" : 1, "details" : { "Value1" : 900, "Value2" : 500 } }
{ "_id" : ObjectId("5eb030a15637cd592b2a4aef"), "id" : 2, "details" : { "Value1" : 1000, "Value2" : 2000 } }
{ "_id" : ObjectId("5eb030a15637cd592b2a4af0"), "id" : 3, "details" : { "Value1" : 80, "Value2" : 90 } }

Updated on: 01-Jul-2020

430 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements