Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Updating a set of documents from a list of key value pairs in MongoDB
To update multiple documents from a list of key-value pairs in MongoDB, use bulk operations with initializeUnorderedBulkOp() to efficiently process multiple updates in a single operation.
Syntax
var bulkUpdateValue = [{"_id": "key1", "field": "value1"}, {"_id": "key2", "field": "value2"}];
var bulkUpdate = db.collection.initializeUnorderedBulkOp();
for (var i = 0; i < bulkUpdateValue.length; i++){
var updateItem = bulkUpdateValue[i];
bulkUpdate.find({_id: updateItem._id}).update({$set: {field: updateItem.field}});
}
bulkUpdate.execute();
Sample Data
db.demo227.insertMany([
{"_id": "101", "Name": "Chris"},
{"_id": "102", "Name": "Bob"}
]);
{
"acknowledged": true,
"insertedIds": {
"0": "101",
"1": "102"
}
}
Display all documents from the collection ?
db.demo227.find();
{ "_id" : "101", "Name" : "Chris" }
{ "_id" : "102", "Name" : "Bob" }
Example: Bulk Update from Key-Value List
Update multiple documents using a predefined list of key-value pairs ?
var bulkUpdateValue = [
{"_id": "101", "Name": "Robert"},
{"_id": "102", "Name": "Sam"}
];
var bulkUpdate = db.demo227.initializeUnorderedBulkOp();
var updateCounter = undefined;
for (var i = 0; i < bulkUpdateValue.length; i++){
updateCounter = bulkUpdateValue[i];
bulkUpdate.find({_id: updateCounter._id}).update({$set: {Name: updateCounter.Name}});
}
bulkUpdate.execute();
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 0,
"nUpserted" : 0,
"nMatched" : 2,
"nModified" : 2,
"nRemoved" : 0,
"upserted" : [ ]
})
Verify Results
Check the updated documents ?
db.demo227.find();
{ "_id" : "101", "Name" : "Robert" }
{ "_id" : "102", "Name" : "Sam" }
Key Points
-
initializeUnorderedBulkOp()creates a bulk operation for better performance with multiple updates. - The loop iterates through the key-value list and queues each update operation.
-
execute()processes all queued operations in a single database call.
Conclusion
Bulk operations with initializeUnorderedBulkOp() provide an efficient way to update multiple documents from a predefined list of key-value pairs, reducing database round trips and improving performance.
Advertisements
