我有一个这样的收藏。
{
"_id" : ObjectId("5d729d41b2f209e6f96034f0"),
"selections" : [
{
"selectionId" : 1.0,
"data" : [
{
"value" : 1.0,
"index" : 1.0
},
{
"value" : 2.0,
"index" : 2.0
}
]
},
{
"selectionId" : 2.0,
"data" : [
{
"value" : 1.0,
"index" : 1.0
},
{
"value" : 2.0,
"index" : 2.0
}
]
}
]
}
我可以进行两个查询来更新两个子文档:
db.getCollection('test').update(
{
"_id": ObjectId("5d729d41b2f209e6f96034f0"),
"selections.selectionId" : 1,
},
{
"$push": {
"selections.$.data" : {
value: 3,
index: 3
}
}
}
)
db.getCollection('test').update(
{
"_id": ObjectId("5d729d41b2f209e6f96034f0"),
"selections.selectionId" : 2,
},
{
"$push": {
"selections.$.data" : {
value: 3,
index: 3
}
}
}
)
是否可以在一个查询中完成?
编辑:我也从第一个答案尝试以下查询:
db.getCollection('test').update(
{
"_id": ObjectId("5d729d41b2f209e6f96034f0")
},
{
$push: {
"selections.$[s1].data": { value: 3, index: 3 },
"selections.$[s2].data": { value: 4, index: 4 }
}
},
{
arrayFilters:
[
{ "s1.selectionId": 1 },
{ "s2.selectionId": 2 }
]
}
)
但它说:
> No array filter found for identifier 's1' in path
> 'selections.$[s1].data'
最佳答案
您需要arrayFilters
和positional filtered运算符:
db.col.update({ "_id": ObjectId("5d729d41b2f209e6f96034f0") },
{ $push: {
"selections.$[s1].data": { value: 3, index: 3 },
"selections.$[s2].data": { value: 3, index: 3 }
} },
{ arrayFilters: [ { "s1.selectionId": 1 }, { "s2.selectionId": 2 } ] }
)