如何在不知道其位置的情况下删除Mongo对象(嵌套2个数组)?

时间:2013-05-28 19:00:27

标签: javascript mongodb meteor

我需要删除嵌入在以下文档中的一个'答案'对象。我有我正在寻找答案的文字。我没有问题的索引或我需要深入研究数组的答案。

例如,我知道我试图深入研究的问题是“这是一个问题”。我想删除的答案是“答案一”。

你会怎么做呢?

以下是MongoDB Doc示例: (测验有问题;问题有答案)

{
    name: "Sample Quiz",
    categories: [
      { name: "testcategory1", description: "this is a test category" }
      ,{ name: "categoryTWO", description: "the second category" }
    ],

    questions: [

      { text: "This is a question."
        ,answers: [
          {text: "Answer One", affected_categories: "testcategory1"}
          ,{text: "Answer Two", affected_categories: "testcategory1"}
          ,{text: "Answer Three", affected_categories: "categoryTWO"}
        ]
      }

      ,{ text: "This is the second question."
        ,answers: [
          {text: "Mepho One", affected_categories: "testcategory1"}
          ,{text: "Answer Toodlydoo", affected_categories: "testcategory1"}
          ,{text: "Lehmen Sumtin", affected_categories: "categoryTWO"}
        ]
      }
    ],
  }

当我删除嵌套了单个级别的项目时(在这种情况下,是一个问题),我能够使用如下查询来执行此操作:

    Quizzes.update(
      { _id: quizID, 'questions.text': questionText },
      { $pull: { questions: {text: questionText }}}
    );

(如此处所述:http://docs.mongodb.org/manual/core/update/#Updating-ModifierOperations,标题为“更新元素而不指定其位置”部分)

我尝试将其扩展为:

Quizzes.update(
  { _id: quizID, 'answers.text': answerText },
  { $pull: { questions: {text: questionText {answers: {text: answerText }}}}}
);

但没有任何运气。

非常感谢任何想法。

1 个答案:

答案 0 :(得分:7)

positional operator与$ pull条件结合使用:

> db.quizzes.update(
      {_id:<quizID>, "questions.text":"This is the second question."}, 
      {$pull:{ "questions.$.answers":{"text":"Answer Toodlydoo"}}}
);

上述方法可以从第二个问题中删除第二个答案。

相关问题