【问题标题】:MongoDB - Update array data in arrayMongoDB - 更新数组中的数组数据
【发布时间】: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.movi​​es.updateOne( { title: 'ironman', 'cmets.text': 'hello' }, { $set: { 'cmets.$.text' : 'nihao' } } ) 但是,回复不能更新方式,??? db.movi​​es.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


【解决方案1】:

您需要$[<identifier>] 过滤位置运算符和arrayFilters 来更新数组中的嵌套文档。

db.collection.update({
  title: "ironman"
},
{
  $set: {
    "comments.$[comment].replies.$[reply].text": "hello"
  }
},
{
  arrayFilters: [
    {
      "comment.replies": {
        $exists: true
      }
    },
    {
      "reply.text": "hi"
    }
  ]
})

Sample Demo on Mongo Playground

【讨论】:

  • 谢谢,解决了这个问题!!
猜你喜欢
  • 2015-08-27
  • 2015-11-28
  • 1970-01-01
  • 1970-01-01
  • 2016-02-09
  • 2018-03-14
  • 1970-01-01
  • 1970-01-01
  • 2020-04-18
相关资源
最近更新 更多