【发布时间】:2021-10-29 09:12:03
【问题描述】:
我正在尝试更新特定文档中数组中的多个元素,其中我有需要更新的元素的索引。
假设我有一个文件:
{
"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