【发布时间】:2022-02-08 21:02:39
【问题描述】:
在 MongoDB 中更新数组内的数组元素的最佳方法是什么?例如,数据如下所示:
{
"_id" : ObjectId("6201396b866ffbf1b84fb8f9"),
"title" : "ironman",
"comments" : [
{
"text" : "nihao",
"replies" : [
{
"text" : "hi"
},
{
"text" : "bonjour"
},
{
"text" : "push replies!!!"
}
]
},
{
"text" : "what??",
"replies" : [
{
"text" : "the"
},
{
"text" : "hey"
}
]
},
{
"text" : "push comments!!!"
}
]
}
我想改变
"comments.replies.text: 'hi'"
到
"comments.replies.text: 'hello'"
如果您想更新回复中的元素,编写查询的最佳方式是什么?
【问题讨论】:
-
有很多数组更新操作符——你使用的然后取决于你的用例。
comments数组字段中有多个replies。您需要告诉您要更新哪个数组元素等(更多详细信息)。见Array Update Operators。 -
我可以使用 db.movies.updateOne( { title: 'ironman', 'cmets.text': 'hello' }, { $set: { 'cmets.$.text' : 'nihao' } } ) 但是,回复不能更新方式,??? db.movies.updateOne( { title: 'ironman', 'cmets.text': 'nihao' }, { { $set: { 'cmets.$.replies.$.text': 'nihao' } } } )
-
您想更新所有回复 - 从 hi 到 hello?您可以使用
arrayFilters选项。 -
哦不,只回复 - 你好。一个元素。 “回复”:[{“text”:“hi”},{“text”:“bonjour”},->“回复”:[{“text”:“hello”},{“text”:“bonjour” },
标签: node.js database mongodb mongodb-query