我试图在节点js中使用猫鼬从嵌套数组中删除值。我的架构结构是这样的:
([{_id: 1,
results: [
{ item: "A", score: 5, answers: [ { q: 1, a: 4 }, { q: 2, a: 6 } ] },
{ item: "B", score: 8, answers: [ { q: 1, a: 8 }, { q: 2, a: 9 } ] }
]
},
{
_id: 2,
results: [
{ item: "C", score: 8, answers: [ { q: 1, a: 8 }, { q: 2, a: 7 } ] },
{ item: "B", score: 4, answers: [ { q: 1, a: 0 }, { q: 2, a: 8 } ] }
]
}])
我想从a为8的答案中删除值。我的查询是
db.collection.update({"results.item":{$in:["C","B"]}},{$pull:{"results.$.answers":{a:8}}})
此查询工作正常,但仅更新一个文档。请帮忙。
我想要的输出是
([{
_id: 1,
results: [
{ item: "A", score: 5, answers: [ { q: 1, a: 4 }, { q: 2, a: 6 } ] },
{ item: "B", score: 8, answers: [ { q: 2, a: 9 } ] }
]
},
{
_id: 2,
results: [
{ item: "C", score: 8, answers: [ { q: 2, a: 7 } ] },
{ item: "B", score: 4, answers: [ { q: 1, a: 0 } ] }
]
}])
提前致谢。
您需要一条语句从MongoDB 3.6或更高版本中过滤掉位置$[<identifier>]
支持:
db.collection.updateMany(
{ "results.item": { "$in": ["C","B"] } },
{ "$pull": { "results.$[el].answers": { "a": 8 } } },
{ "arrayFilters": [{ "el.item": { "$in": ["C", "B"] } }] }
)
结果是:
{
"_id" : 1,
"results" : [
{
"item" : "A",
"score" : 5,
"answers" : [
{
"q" : 1,
"a" : 4
},
{
"q" : 2,
"a" : 6
}
]
},
{
"item" : "B",
"score" : 8,
"answers" : [
{
"q" : 2,
"a" : 9
}
]
}
]
}
{
"_id" : 2,
"results" : [
{
"item" : "C",
"score" : 8,
"answers" : [
{
"q" : 2,
"a" : 7
}
]
},
{
"item" : "B",
"score" : 4,
"answers" : [
{
"q" : 1,
"a" : 0
}
]
}
]
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句