I was surprised to find that the following example code only updates a single document:
> db.test.save({"_id":1, "foo":"bar"});
> db.test.save({"_id":2, "foo":"bar"});
> db.test.update({"foo":"bar"}, {"$set":{"test":"success!"}});
> db.test.find({"test":"success!"}).count();
1
I know I can loop through and keep updating until they're all changed, but that seems terribly inefficient. Is there a better way?
All latest versions of mongodb updateMany() is working fine
For versions of mongodb 3.2+ you can use method updateMany() to update multiple documents,
http://answerexpress.blogspot.com/2018/09/mongodb-how-to-update-multiple.html
In the MongoDB Client, type:
New in version 3.2
Params::
Keyword argument
multi
not takenI've created a way to do this with a better interface.
db.collection.find({ ... }).update({ ... })
-- multi updatedb.collection.find({ ... }).replace({ ... })
-- single replacementdb.collection.find({ ... }).upsert({ ... })
-- single upsertdb.collection.find({ ... }).remove()
-- multi removeYou can also apply limit, skip, sort to the updates and removes by chaining them in beforehand.
If you are interested, check out Mongo-Hacker
For Mongo version > 2.2, add a field multi and set it to true
UPDATE as of V2.2, the update function takes the following form:
The selected answer no longer applies.
https://docs.mongodb.com/manual/reference/method/db.collection.update/