
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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" }
- Related Questions & Answers
- How to update value of a key in a list of a json in MongoDB?
- How to sum the value of a key across all documents in a MongoDB collection?
- Update objects in a MongoDB documents array (nested updating)?
- Updating Nested Embedded Documents in MongoDB?
- Find a value in lowercase from a MongoDB collection with documents
- MongoDB query to get specific list of names from documents where the value of a field is an array
- Find value above a specific value in MongoDB documents?
- How to extract subset of key-value pairs from Python dictionary object?
- MongoDB Aggregate sum of values in a list of dictionaries for all documents?
- How to read a specific key-value pair from a MongoDB collection?
- Find all duplicate documents in a MongoDB collection by a key field?
- Evaluate one of more values from a MongoDB collection with documents
- How to get a key/value data set from a HTML form?
- Create a TreeMap in Java and add key-value pairs
- Find MongoDB documents where elements of an array have a specific value?
Advertisements