首页 > 解决方案 > 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 } ] }
   ]
}

我怎样才能删除“答案”而不是“结果”的元素?请帮我!


我已经尝试了很多次,但它只是可以删除“结果”的元素。

db.collections.update(
  { "item":"C" },
  {$pull:{"results" :{ "answers": {   $elemMatch: { "q": 1 } }} }}
)

我无法获取子数组中元素的索引。实际上有一个对象存储在子数组中,我想通过它的 id 删除该对象。


我使用C#驱动这是我的第一个问题,描述可能不是很清楚,请见谅

标签: c#mongodb

解决方案


您可以尝试使用$pull

db.your_collection.update(
   { _id : 2 },
   { $pull : { "results.0.answers" : { "q": 1 } } }
);

这基本上做的是,搜索带有 的文档_id: 2,然后从数组中pulls的文档中删除 ( ),results.X.answers其中 X 是index条件{ "q" : 1 }为真的结果数组的。


推荐阅读