Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: unconditional updates?

Tags:

mongodb

This seems like a silly question but I haven't yet found the answer. If I simply wanted to add the same field->value to EVERY record in a MongoDB collection, what would be the appropriate shell command to do so? I tried doing a multi update with a blank query ({}) but that resulted in this error:

multi update only works with $ operators

I'm a bit puzzled about how to get around this. Any suggestions?

like image 719
Matt Diamond Avatar asked Apr 07 '11 21:04

Matt Diamond


People also ask

Does MongoDB update automatically?

No, there is no such thing (autoupdate) in MongoDB. It must be done with application or script.

Can we update _ID in MongoDB?

You cannot update it but you can save a new id and remove the old id.

How does updates work in MongoDB?

MongoDB Update method is used to update the document from the collection, and the update method will update the value of the existing document. We have used a $set operator at the time of updating the document. We can update a single document by using an update or updateOne method.


1 Answers

The error says it all: You can only modify multiple documents using the $ modifier operators. You probably had something like this:

> db.coll.update({ }, { a: 'b' }, false, true); 

Which would normally replace the first object in the collection with { a: 'b' } if multi was false. You wouldn't want to replace all the objects in your collection with the same document!

Use the $set operator instead:

> db.coll.update({ }, { '$set': { a: 'b' } }, false, true); 

This will set the a property of every document (creating it as necessary) to 'b'.

like image 191
Cameron Avatar answered Sep 18 '22 15:09

Cameron