簡體   English   中英

僅刪除(更新查詢)數組 mongodb 數組中的特定元素?

[英]Remove (Update query) only particular element in array of array mongodb?

我的輸入數據

{
   _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 } ] }
   ]
}

預期更新查詢 output

{
   _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 但數據不符合預期。 下面代碼的 output 只是刪除了整個元素而不是子元素

db.collection.update(
  { },
  { $pull: { results: { $elemMatch: { score: 8 , item: "B" } } } },
  { multi: true }
)

您使用的查詢是從結果數組中刪除任何 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 } ] }
   ]
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM