【问题标题】:Update multiple array elements by index in a document in MongoDB通过 MongoDB 文档中的索引更新多个数组元素
【发布时间】:2021-10-29 09:12:03
【问题描述】:

我正在尝试更新特定文档中数组中的多个元素,其中我有需要更新的元素的索引。

MongoDB Playground Link

假设我有一个文件:

{
    "key": 1,
    "questions": [
      {
        "text": "first",
      },
      {
        "text": "second",
      },
      {
        "text": "third",
        "answered": "balloon",
      },
    ],
},

我想更新问题 2 和 3(按索引号)并在项目中添加键、值对。
预期输出:

{
    "key": 1,
    "questions": [
      {
        "text": "first",
      },
      {
        "text": "second",
        "answered": "second answer", //Added field
      },
      {
        "text": "third",
        "answered": "third answer", //Updated field
      },
    ],
},

到目前为止我所尝试的:

db.collection.update({
  "key": 1,
},
{
  $set: {
    "questions.$[elem0].answered": "second answer",
    "questions.$[elem1].answered": "third answer",
  }
},
{
  arrayFilters: [
    {
      "elem0": 1 //Trying to update index position 1
    },
    {
      "elem1": 2 //Trying to update index position 2
    }
  ],
})

我希望操作是原子的,而不是对我正在更新的每个项目进行多个查询。所有项都属于同一个文档的嵌套数组。

【问题讨论】:

    标签: mongodb mongoose mongodb-query


    【解决方案1】:

    $set

    db.collection.update({
      "key": 1
    },
    {
      $set: {
        "questions.1.answered": "second answer",
        "questions.2.answered": "third answer"
      }
    })
    

    mongoplayground

    【讨论】:

    • 我想按索引位置更新,而不是通过匹配任何其他字段。那可能吗?因为你提到的“文本”,我没有以前的任何其他细节,只有索引。
    • 我更新了我的答案,你不需要arrayfilters
    猜你喜欢
    • 2017-07-02
    • 2016-11-04
    • 2022-12-09
    • 2014-04-01
    • 2022-12-05
    • 1970-01-01
    • 2016-11-18
    • 2014-03-27
    • 1970-01-01
    相关资源
    最近更新 更多