使用文档中另一个字段的值更新字段 [英] Update field with another field's value in the document
问题描述
我有一个集合 t1
,其架构中有以下字段
I have a collection t1
with the following fields in its schema
_id, field1, field1
我想像sql一样设置field2
的值field1
:
I want set field2
's value field1
like sql:
update t1 set field1=field2;
如何在 MongoDB 中执行此操作?
How do I do it in MongoDB?
推荐答案
这里有好消息和坏消息.
Good and bad news here.
坏消息是,AFAIK 不能通过单个 update() 调用来实现 - mongo 不支持在更新中引用当前对象.
Bad news is that AFAIK you can't do it with a single update() call - mongo doesn't support referring to current object in update.
好消息是还有其他方法可以做到,例如你可以运行一个 forEach 循环:
Good news is that there are other ways to do it, e.g. you can run a forEach loop:
db.item.find(conditions...).snapshot().forEach( function (doc) {
doc.field1 = doc.field2;
db.item.save(doc);
});
您可以在管理 shell('mongo' 命令)中运行 forEach,或者通过您的特定驱动程序的一些方法(例如在 PHP 中,我希望它与 mongodb.execute() 一起使用,如下所述:http://www.php.net/manual/en/mongodb.execute.php)
You can run forEach in the admin shell ('mongo' command), or through some of the methods of your specific driver (e.g. in PHP I'd expect it to work with mongodb.execute() as described in here: http://www.php.net/manual/en/mongodb.execute.php)
这篇关于使用文档中另一个字段的值更新字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!