How to update multiple documents in MongoDB?


You need to use multi:true to update multiple documents. Let us first create a collection with documents −

> db.multiUpdateDemo.insertOne({"ClientName":"John","ClientAge":29});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cda5bc0b50a6c6dd317adc8")
}
> db.multiUpdateDemo.insertOne({"ClientName":"Carol","ClientAge":31});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cda5bc1b50a6c6dd317adc9")
}
> db.multiUpdateDemo.insertOne({"ClientName":"John","ClientAge":39});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cda5bc3b50a6c6dd317adca")
}
> db.multiUpdateDemo.insertOne({"ClientName":"John","ClientAge":41});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cda5bc5b50a6c6dd317adcb")
}
> db.multiUpdateDemo.insertOne({"ClientName":"David","ClientAge":35});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cda5bc6b50a6c6dd317adcc")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.multiUpdateDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cda5bc0b50a6c6dd317adc8"),
   "ClientName" : "John",
   "ClientAge" : 29
}
{
   "_id" : ObjectId("5cda5bc1b50a6c6dd317adc9"),
   "ClientName" : "Carol",
   "ClientAge" : 31
}
{
   "_id" : ObjectId("5cda5bc3b50a6c6dd317adca"),
   "ClientName" : "John",
   "ClientAge" : 39
}
{
   "_id" : ObjectId("5cda5bc5b50a6c6dd317adcb"),
   "ClientName" : "John",
   "ClientAge" : 41
}
{
   "_id" : ObjectId("5cda5bc6b50a6c6dd317adcc"),
   "ClientName" : "David",
   "ClientAge" : 35
}

Following is the query to perform multi-update. The ClientName “John” for 3 clients will now have updated age using the below query −

> db.multiUpdateDemo.update({'ClientName': 'John'}, {$set: {'ClientAge': 34}}, {multi: true});
WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })

Let us check the documents once again −

> db.multiUpdateDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cda5bc0b50a6c6dd317adc8"),
   "ClientName" : "John",
   "ClientAge" : 34
}
{
   "_id" : ObjectId("5cda5bc1b50a6c6dd317adc9"),
   "ClientName" : "Carol",
   "ClientAge" : 31
}
{
   "_id" : ObjectId("5cda5bc3b50a6c6dd317adca"),
   "ClientName" : "John",
   "ClientAge" : 34
}
{
   "_id" : ObjectId("5cda5bc5b50a6c6dd317adcb"),
   "ClientName" : "John",
   "ClientAge" : 34
}
{
   "_id" : ObjectId("5cda5bc6b50a6c6dd317adcc"),
   "ClientName" : "David",
   "ClientAge" : 35
}

Updated on: 30-Jul-2019

300 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements