MongoDB:无条件更新? [英] MongoDB: unconditional updates?

查看:462
本文介绍了MongoDB:无条件更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是一个愚蠢的问题,但我尚未找到答案.如果我只是想向MongoDB集合中的每条记录添加相同的field-> value,那么合适的shell命令是什么呢?我尝试使用空白查询({})进行多次更新,但导致此错误:

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:

多次更新仅适用于$运算符

我对如何解决这个问题感到有些困惑.有什么建议吗?

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

推荐答案

错误说明了一切:您只能使用

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);

如果multi为false,通常会使用{ a: 'b' } 替换集合中的第一个对象.您不想用同一文档替换集合中的所有对象!

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!

使用 $set运算符代替:

Use the $set operator instead:

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

这会将每个文档的a属性(根据需要创建)设置为'b'.

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

这篇关于MongoDB:无条件更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆