MongoDB: How to update multiple documents with a single command?
Solution 1:
Multi update was added recently, so is only available in the development releases (1.1.3). From the shell you do a multi update by passing true
as the fourth argument to update()
, where the the third argument is the upsert argument:
db.test.update({foo: "bar"}, {$set: {test: "success!"}}, false, true);
For versions of mongodb 2.2+ you need to set option multi true to update multiple documents at once.
db.test.update({foo: "bar"}, {$set: {test: "success!"}}, {multi: true})
For versions of mongodb 3.2+ you can also use new method updateMany()
to update multiple documents at once, without the need of separate multi
option.
db.test.updateMany({foo: "bar"}, {$set: {test: "success!"}})
Solution 2:
Starting in v3.3 You can use updateMany
db.collection.updateMany(
<filter>,
<update>,
{
upsert: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ]
}
)
In v2.2, the update function takes the following form:
db.collection.update(
<query>,
<update>,
{ upsert: <boolean>, multi: <boolean> }
)
https://docs.mongodb.com/manual/reference/method/db.collection.update/
Solution 3:
For Mongo version > 2.2, add a field multi and set it to true
db.Collection.update({query},
{$set: {field1: "f1", field2: "f2"}},
{multi: true })
Solution 4:
I've created a way to do this with a better interface.
-
db.collection.find({ ... }).update({ ... })
-- multi update -
db.collection.find({ ... }).replace({ ... })
-- single replacement -
db.collection.find({ ... }).upsert({ ... })
-- single upsert -
db.collection.find({ ... }).remove()
-- multi remove
You can also apply limit, skip, sort to the updates and removes by chaining them in beforehand.
If you are interested, check out Mongo-Hacker