I just started learning mongo, and tought that {} refer to all documents in the collection, and was thinking that this query: db.foo.update( {}, { $set: { letter : 'a' } }, { multi : true } ); will update all documents in collection.
Just in case I’m using MongoDB shell version: 2.0.4
> for (i=0; i<3; i++) db.foo.insert({ num : i });
> db.foo.find()
{ "_id" : ObjectId("510debe5ccc97edd4aca03dc"), "num" : 0 }
{ "_id" : ObjectId("510debe5ccc97edd4aca03dd"), "num" : 1 }
{ "_id" : ObjectId("510debe5ccc97edd4aca03de"), "num" : 2 }
> db.foo.update( {}, { $set: { letter : 'a' } }, { multi : true } );
> db.foo.find()
{ "_id" : ObjectId("510debe5ccc97edd4aca03dd"), "num" : 1 }
{ "_id" : ObjectId("510debe5ccc97edd4aca03de"), "num" : 2 }
{ "_id" : ObjectId("510debe5ccc97edd4aca03dc"), "letter" : "a", "num" : 0 }
The line
does not do what you think!
The third argument of
updateis supposed to be whether or not the update is an upsert. If the third argument is truthy, you do an upsert. If falsy you do not. You passed in an object ({multi: true}) which is truthy, so you are doing an upsert.The fourth argument is multi. You did not supply a fourth argument, and in JavaScript, this means it is undefined, which is falsy, so your query does not do a multi!
You meant to write:
This is the way you make a multi update in JavaScript.