1

我的输入数据

{
   _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 }
)
4

1 回答 1

1

您使用的查询是从结果数组中删除任何 score = 'B' 和 item = '8' 的项目。

answers 数组嵌入在 results 数组中,因此如果您需要从 answers 数组中删除一些元素,那么您必须将检查添加到答案而不是结果中,例如,如果您需要删除具有 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 } ] }
   ]
}
于 2020-04-04T03:38:24.080 回答