Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Updating a set of documents from a list of key value pairs in MongoDB
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" }Advertisements