randombits
randombits

Reputation: 48450

MongoDB how to do this where clause update

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?

Upvotes: 15

Views: 18929

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311855

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}})

Upvotes: 29

Related Questions