MongoDB - 使用$ set更新子文档 [英] MongoDB - update sub document using $set

查看:131
本文介绍了MongoDB - 使用$ set更新子文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个文件:

{ "data" : "AP1IUY9Bfp", "me" : { "something" : "somevalue" } }

我有这个对象:

webpage: 'stackoverflow'

我该怎么办? $ push / $将此字段设置为document.me,因此最终结果将等于:

How can I $push/$set this field into document.me, so the final result will equal:

{ "data" : "AP1IUY9Bfp", "me" : { "something" : "somevalue", "webpage": "stackoverflow" } }

如果我使用 $ set 尝试此操作,请执行以下操作:

If I try this using $set, like this:

db.collection('doc').update({id: 'AP1IUY9Bfp'}, {'$set': {'me': webpage: 'stackoverflow'}}

结果等于:

{ "data" : "AP1IUY9Bfp", "me" : { "webpage" : "stackoverflow" } }

(它覆盖该字段)

谢谢!

推荐答案

你想要什么要做的就是喜欢这样:

What you'll want to do is something like this:

{'$set': {'me.webpage': 'stackoverflow'} }

注意唯一的区别是我使用点符号指向子文档。

Note the only difference is that I'm using dot notation to point to a sub-document.

想想它就像在Mongo之外的普通JSON对象一样。您使用点表示法来访问对象的属性 - mongo的工作方式相同。

Think about it as you would a normal JSON object outside of Mongo. You use dot notation to access properties of objects - mongo works the same way.

这是有关子文档和mongo中点符号的相关文档的链接 - http://docs.mongodb.org/manual/core/document/#dot-notation

Here is a link to the relevant documentation regarding subdocuments and the dot notation in mongo - http://docs.mongodb.org/manual/core/document/#dot-notation


点符号



MongoDB使用点表示法访问数组的元素和访问子文档的字段。

Dot Notation

MongoDB uses the dot notation to access the elements of an array and to access the fields of a subdocument.

...

访问带有点表示法的子文档的字段,将
子文档名称与点(。)和字段名称连接起来,并用
引号括起来:

To access a field of a subdocument with dot-notation, concatenate the subdocument name with the dot (.) and the field name, and enclose in quotes:

'< subdocument>。< field>'

这篇关于MongoDB - 使用$ set更新子文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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