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?
The MongoDB $where operator is used to match documents that satisfy a JavaScript expression. A string containing a JavaScript expression or a JavaScript function can be pass using the $where operator.
Use the $where operator to pass either a string containing a JavaScript expression or a full JavaScript function to the query system. The $where provides greater flexibility, but requires that the database processes the JavaScript expression or function for each document in the collection.
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}})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With