gpt4 book ai didi

javascript - MongoDB - 使用 $set 更新子文档

转载 作者:行者123 更新时间:2023-11-30 06:26:07 25 4
gpt4 key购买 nike

我有这个文件:

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

我有这个对象:

webpage: 'stackoverflow'

我怎样才能$push/$set这个字段到document.me中,所以最后的结果会等于:

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

如果我尝试使用 $set,像这样:

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

结果等于:

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

(覆盖字段)

谢谢!

最佳答案

你想要做的是这样的:

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

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

将其视为 Mongo 之外的普通 JSON 对象。您使用点表示法访问对象的属性 - mongo 的工作方式相同。

这是有关子文档和 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.

...

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

关于javascript - MongoDB - 使用 $set 更新子文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20946001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com