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

使用するクエリは、スコア = '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 } ] }
   ]
}
于 2020-04-04T03:38:24.080 に答える