Javascript 是否仅删除(更新查询)mongodb数组中的特定元素?
我的输入数据Javascript 是否仅删除(更新查询)mongodb数组中的特定元素?,javascript,arrays,mongodb,updates,arrayofarrays,Javascript,Arrays,Mongodb,Updates,Arrayofarrays,我的输入数据 { _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, an
{
_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 } ] }
]
}
预期的更新查询输出
{
_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 }] }
]
}
{
_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 } }
]
}
尝试在这些mongoDb手册中查询$pull,但数据不符合预期。下面代码的输出只是删除整个元素,而不是子元素
db.collection.update(
{ },
{ $pull: { results: { $elemMatch: { score: 8 , item: "B" } } } },
{ multi: true }
)
您使用的查询正在从结果数组中删除得分为“B”且项为“8”的任何项 答案数组嵌入在结果数组中,因此如果需要从答案数组中删除某些元素,则必须将检查添加到答案,而不是结果 例如,如果需要删除q=1和a=8的答案 那么查询应该是这样的:
db.collection.update(
{ },
{ $pull: { 'results.$[].answers': { q: 1, a: 8 } } },
{ multi: true }
)
这将更新答案数组,而不是结果数组,
此查询的结果将是
{
_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 }, { q: 2, a: 8 } ] }
]
}
你想删除什么?什么版本的MongoDB?