MongoDB: How to update multiple documents with a single command?
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!"}})
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/