14

I have a collection named 'Foo'. I'd like to update every document in the Foo collection that has a bar value of 100 to 1000. What's the best way to run this update in MongoDB to get an efficient update?

randombits
  • 47,058
  • 76
  • 251
  • 433
  • What you are trying to do is not possible with a single update statement. You can use another method as in this post: - http://stackoverflow.com/questions/8342725/how-to-update-a-field-in-mongodb-using-existing-value – Rohit Jain Dec 17 '12 at 19:59
  • I don't think that's correct; see the response below. – paulmelnikow Dec 17 '12 at 22:59
  • Possible duplicate of [MongoDB: How to update multiple documents with a single command?](https://stackoverflow.com/questions/1740023/mongodb-how-to-update-multiple-documents-with-a-single-command) – yAnTar Jun 11 '18 at 09:19

1 Answers1

28

Use the $set operator to do that:

db.foo.update({bar: 100}, {$set: {bar: 1000}}, false, true)

The fourth parameter sets the multi option to true so that you update all matching documents, not just the first one.

3.2 UPDATE

Recent MongoDB versions provide an updateMany method that is a bit more intuitive:

db.foo.updateMany({bar: 100}, {$set: {bar: 1000}})
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471