Updating a set of documents from a list of key value pairs in MongoDB

MongoDBDatabaseBig Data Analytics

Let us create a collection with documents −

> db.demo227.insertOne({"_id":"101","Name":"Chris"});
{ "acknowledged" : true, "insertedId" : "101" }
> db.demo227.insertOne({"_id":"102","Name":"Bob"});
{ "acknowledged" : true, "insertedId" : "102" }

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

> db.demo227.find();

This will produce the following output −

{ "_id" : "101", "Name" : "Chris" }
{ "_id" : "102", "Name" : "Bob" }

Following is the query to update a set of documents from a 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" : [ ]
})

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

> db.demo227.find();

This will produce the following output −

{ "_id" : "101", "Name" : "Robert" }
{ "_id" : "102", "Name" : "Sam" }
raja
Published on 30-Mar-2020 12:59:58
Advertisements