In this blog post we are going to learn the process of updating multiple documents in MongoDB. MongoDB provides us with update() function to achieve the same.

Here are few use cases :

db.users.find();
{ "_id" : ObjectId("537da62d770359c2fb4668e2"), "name" : "Neeraj Bhatt", "age" : "28" }
{ "_id" : ObjectId("537d442d770359c2fb4668e2"), "name" : "Neeraj Bhatt", "age" : "26" }

Now let us update record and add another field into the document. Here we are adding location field in the users document.

db.users.update({name:'Neeraj Bhatt'},{$set:{'location':'Noida'}});	
// I am willing to update location to Noida for all people named Neeraj Bhatt.
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Now querying the collection will provide us with the new field added in the matching document.

db.users.find();
{ "_id" : ObjectId("537da62d770359c2fb4668e2"), "name" : "Neeraj Bhatt", "age" : "28", "location" : "Noida" }
{ "_id" : ObjectId("537d442d770359c2fb4668e2"), "name" : "Neeraj Bhatt", "age" : "26" }

But above result shows that only one record was updated and i know for sure i have 2 guys with same name. So how do i update both of them in one go ? We need to use “multi” parameter

db.users.update({name:'Neeraj Bhatt'},{$set:{'location':'Noida'}},{multi:true});
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })

db.users.find();
{ "_id" : ObjectId("537da62d770359c2fb4668e2"), "name" : "Neeraj Bhatt", "age" : "28", "location" : "Noida" }
{ "_id" : ObjectId("537d442d770359c2fb4668e2"), "name" : "Neeraj Bhatt", "age" : "26", "location" : "Noida" }