Update multiple rows in a single MongoDB query?


Use the concept of initializeUnorderedBulkOp(). Let us first create a collection with documents −

>db.upDateMultipleRowsDemo.insertOne({"CustomerName":"John","CustomerPurchaseAmount":500});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd6ceb06d78f205348bc626")
}
>db.upDateMultipleRowsDemo.insertOne({"CustomerName":"Chris","CustomerPurchaseAmount":700});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd6ceb26d78f205348bc627")
}
>db.upDateMultipleRowsDemo.insertOne({"CustomerName":"David","CustomerPurchaseAmount":50});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd6ceb36d78f205348bc628")
}
>db.upDateMultipleRowsDemo.insertOne({"CustomerName":"Larry","CustomerPurchaseAmount":1900});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd6ceb46d78f205348bc629")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.upDateMultipleRowsDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cd6ceb06d78f205348bc626"),
   "CustomerName" : "John",
   "CustomerPurchaseAmount" : 500
}
{
   "_id" : ObjectId("5cd6ceb26d78f205348bc627"),
   "CustomerName" : "Chris",
   "CustomerPurchaseAmount" : 700
}
{
   "_id" : ObjectId("5cd6ceb36d78f205348bc628"),
   "CustomerName" : "David",
   "CustomerPurchaseAmount" : 50
}
{
   "_id" : ObjectId("5cd6ceb46d78f205348bc629"),
   "CustomerName" : "Larry",
   "CustomerPurchaseAmount" : 1900
}

Following is the query to update multiple rows in a single query −

> var manyUpdateValue = db.upDateMultipleRowsDemo.initializeUnorderedBulkOp();

> manyUpdateValue.find({ _id: ObjectId("5cd6ceb06d78f205348bc626")}).updateOne({$set:{"CustomerName":"Bob" }});

> manyUpdateValue.find({ _id: ObjectId("5cd6ceb36d78f205348bc628")}).updateOne({$set:{"CustomerPurchaseAmount":56544444}});

> manyUpdateValue.execute();
BulkWriteResult({
   "writeErrors" : [ ],
   "writeConcernErrors" : [ ],
   "nInserted" : 0,
   "nUpserted" : 0,
   "nMatched" : 2,
   "nModified" : 2,
   "nRemoved" : 0,
   "upserted" : [ ]
})

Let us check all the documents once again −

> db.upDateMultipleRowsDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cd6ceb06d78f205348bc626"),
   "CustomerName" : "Bob",
   "CustomerPurchaseAmount" : 500
}
{
   "_id" : ObjectId("5cd6ceb26d78f205348bc627"),
   "CustomerName" : "Chris",
   "CustomerPurchaseAmount" : 700
}
{
   "_id" : ObjectId("5cd6ceb36d78f205348bc628"),
   "CustomerName" : "David",
   "CustomerPurchaseAmount" : 56544444
}
{
   "_id" : ObjectId("5cd6ceb46d78f205348bc629"),
   "CustomerName" : "Larry",
   "CustomerPurchaseAmount" : 1900
}

Updated on: 30-Jul-2019

306 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements