MongoDB 使用 object 中的 existing/current 值将包含字符串元素的数组 change/convert 更新为包含 object 元素的数组

MongoDB update change/convert an array with string elements to an array with object elements using the existing/current value within that object

我正在学习 MongoDB (5.6) 并且有一个 collection 文档如下:

[
  {
    "_id": {
      "$oid": "62642b53df03395a48eba4d3"
    },
    "title": "Chemical Biology",
    "authors": [
      "625861411edf9d62ec72c889"
    ],
    "year": 1947,
    "sentences": [
      "sentence 001",
      "sentence 002"
    ]
  }
]

我想将数组“sentences”更新为 object 的数组(在 collection 的所有文档中)使用现有的价值。我希望它是这样的:

[
  {
    "_id": {
      "$oid": "62642b53df03395a48eba4d3"
    },
    "title": "Chemical Biology",
    "authors": [
      "625861411edf9d62ec72c889"
    ],
    "year": 1947,
    "sentences": [
      {
        "order_chem": 50,
        "order_bio": 50,
        "order_science": 50,
        "order_school": 50,
        "value": "sentence 001"
      },
      {
        "order_chem": 50,
        "order_bio": 50,
        "order_science": 50,
        "order_school": 50,
        "value": "sentence 002"
      }
    ],
  }
]

到目前为止,这个查询是我最接近的结果:

db.collection.update({},
[
  {
    "$set": {
      "sentences": {
        "value": {"$arrayElemAt": ["$sentences", 0]},
        //"value": "$sentences",
        "order_chem": 50,
        "order_bio": 50,
        "order_science": 50,
        "order_school": 50
      }
    }
  }
],
{
  multi: true
})

这当然几乎是我想要的,但不完全是(因为我硬引用索引为 0)。如果我能在每个循环中访问数组句子的当前 index/value,我就能得到想要的结果。

[
  {
    "_id": ObjectId("62642b53df03395a48eba4d3"),
    "authors": [
      "625861411edf9d62ec72c889"
    ],
    "sentences": [
      {
        "order_chem": 50,
        "order_bio": 50,
        "order_science": 50,
        "order_school": 50,
        "value": "sentence 001",
      },
      {
        "order_chem": 50,
        "order_bio": 50,
        "order_science": 50,
        "order_school": 50,
        "value": "sentence 001"
      }
    ],
    "title": "Chemical Biology",
    "year": 1947
  }
]

Mongo Playground

如何在每个循环中访问确切的数字数组索引或 element/content?

感谢您耐心阅读到这里。您能否建议如何使用数值数组字段的 current/existing 值并使用当前值将同一字段转换为 object 数组?

提前致谢。

当您使用聚合管道进行更新时,您可以使用 $map 来迭代 sentences 和 return 新 sentences 数组中的元素。

db.collection.update({},
[
  {
    "$set": {
      "sentences": {
        $map: {
          input: "$sentences",
          in: {
            "order_chem": 50,
            "order_bio": 50,
            "order_science": 50,
            "order_school": 50,
            value: "$$this"
          }
        }
      }
    }
  }
],
{
  multi: true
})

Sample Mongo Playground