用文档中另一个字段的值更新字段 [英] Update field with another field's value in the document

查看:50
本文介绍了用文档中另一个字段的值更新字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个集合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...).forEach( function (doc) {
  doc.field1 = doc.field2; 
  db.item.save(doc); 
});

您可以在admin shell('mongo'命令)中运行forEach,也可以通过特定驱动程序的某些方法运行(例如,在PHP中,我希望它可以与mongodb.execute()一起使用,如下所述: http://www.php.net/manual/zh/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屋!

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