简体   繁体   English

MongoDB-使用$ set更新子文档

[英]MongoDB - update sub document using $set

I have this document: 我有这个文件:

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

I have this object: 我有这个对象:

webpage: 'stackoverflow'

How can I $push/$set this field into document.me, so the final result will equal: 我如何$ push / $ set这个字段到document.me,所以最终结果将等于:

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

If I try this using $set , like this: 如果我使用$set尝试这样做,像这样:

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

The result equals: 结果等于:

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

(it overwrites the field) (它会覆盖该字段)

Thanks! 谢谢!

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. 请注意,唯一的区别是我使用点表示法指向子文档。

Think about it as you would a normal JSON object outside of Mongo. 像对待Mongo之外的普通JSON对象一样考虑它。 You use dot notation to access properties of objects - mongo works the same way. 您可以使用点表示法来访问对象的属性-mongo的工作方式相同。

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

Dot Notation 点表示法

MongoDB uses the dot notation to access the elements of an array and to access the fields of a subdocument. MongoDB使用点表示法来访问数组的元素并访问子文档的字段。

... ...

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>'

一定不是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM