MongoDB:无条件更新?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5587677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MongoDB: unconditional updates?
提问by Matt Diamond
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:
这似乎是一个愚蠢的问题,但我还没有找到答案。如果我只是想将相同的 field->value 添加到 MongoDB 集合中的每条记录,那么合适的 shell 命令是什么?我尝试使用空白查询 ({}) 进行多更新,但导致此错误:
multi update only works with $ operators
多重更新仅适用于 $ 运算符
I'm a bit puzzled about how to get around this. Any suggestions?
我对如何解决这个问题感到有些困惑。有什么建议?
回答by Cameron
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 replacethe 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!
这通常会用if为 false替换集合中的第一个对象。您不想用同一个文档替换集合中的所有对象!{ a: 'b' }
multi
Use the $set
operatorinstead:
改用$set
运算符:
> db.coll.update({ }, { '$set': { a: 'b' } }, false, true);
This will set the a
property of every document (creating it as necessary) to 'b'
.
这会将a
每个文档的属性(根据需要创建)设置为'b'
.