Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB how to do this where clause update

Tags:

mongodb

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?

like image 750
randombits Avatar asked Dec 17 '12 19:12

randombits


People also ask

Can we use where clause in MongoDB?

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.

What is equivalent command for where clause in MongoDB?

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.


1 Answers

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}})
like image 91
JohnnyHK Avatar answered Nov 16 '22 03:11

JohnnyHK