MongoDB: unconditional updates?

Mongodb

Mongodb Problem Overview


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?

Mongodb Solutions


Solution 1 - Mongodb

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'.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatt DiamondView Question on Stackoverflow
Solution 1 - MongodbCameronView Answer on Stackoverflow