MongoDB - 仅更新 DBRef 字段类型中的 $ref [英] MongoDB - Updating only $ref from DBRef field type

查看:36
本文介绍了MongoDB - 仅更新 DBRef 字段类型中的 $ref的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要更新多个集合文档的字段.该字段是一个 DBRef,我只需要更改 $ref 字段值.

I need to update a field of multiple collection documents. The field is a DBRef and I just need to change the $ref field value.

其中一个文件是这样的:

One of the documents is like this:

{ "_id" : { "$oid" : "50ab682bd3155502a75c7cf6"} , "codeId" : { "$ref":版本",$id":{$oid":511cb7d5696bdbaf4c85ebb1"}}}

{ "_id" : { "$oid" : "50ab682bd3155502a75c7cf6"} , "codeId" : { "$ref" : "version" , "$id" : { "$oid" : "511cb7d5696bdbaf4c85ebb1"}}}

我想要的最终结果是这样的:

The final result I want is this:

{ "_id" : { "$oid" : "50ab682bd3155502a75c7cf6"} , "codeId" : { "$ref": "code" , "$id" : { "$oid" : "511cb7d5696bdbaf4c85ebb1"}}}

{ "_id" : { "$oid" : "50ab682bd3155502a75c7cf6"} , "codeId" : { "$ref" : "code" , "$id" : { "$oid" : "511cb7d5696bdbaf4c85ebb1"}}}

我已经这样试过了:

db.collection.update(
   {}, 
   {$set:{"codeId":{$ref:"code"}}},
   false,
   true
);

问题是$id丢失了(设置为null)

The problem is that the $id is lost (set as null)

{ "_id" : { "$oid" : "50ab682bd3155502a75c7cf6"} , "codeId" : { "$ref": "code" , "$id" : { "$oid" : null}}}

{ "_id" : { "$oid" : "50ab682bd3155502a75c7cf6"} , "codeId" : { "$ref" : "code" , "$id" : { "$oid" : null}}}

如何保留 $id?

谢谢

推荐答案

您可以使用点表示法来更新嵌套文档.请注意,无论何时使用点符号,都应将其放在引号之间.

You can use dot notation in order to update the nested document. Note that, whenever the dot notation is used, it should be put between quotes.

db.collection.update(
   {}, 
   { $set:{
       "codeId.$ref":"code"
     }
   },
   false,
   true
);

您可以阅读有关数据库引用的更多信息.

You can read more about Database References.

这篇关于MongoDB - 仅更新 DBRef 字段类型中的 $ref的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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