MongoDB: unconditional updates?

This seems like a silly question, but I haven't found an answer yet. If I just wanted to add the same field-> value to EVERY entry in the MongoDB collection, what would be a suitable shell command for? I tried to make some updates with an empty request ({}), but this led to this error:

multiple updates only work with $ operators

I am a little puzzled by how to get around this. Any suggestions?

+46
mongodb
Apr 7 2018-11-11T00:
source share
1 answer

The error says it all: you can only change a few documents using the $ modifier operators. You probably had something like this:

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

Which usually replaces the first object in the collection with { a: 'b' } if multi was false. You will not want to replace all objects in your collection with the same document!

Use the $set operator instead:

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

This will create a property of each document (if necessary, create it) before 'b' .

+97
Apr 7 2018-11-11T00:
source share



All Articles