Dave C. Dave C. - 19 days ago 6
Javascript Question

How To Delete Mongo Object (nested 2 arrays down) without knowing its position?

I need to remove one of the 'answers' objects nested in the Doc below. I have the text of the answer I'm looking for. I don't have the index of the question OR the answer that I need to drill down into the arrays.

For example, I know that the text of the question I'm trying to drill down into is "This is a question." and the answer I want to delete is "Answer One".

How would you go about doing that?

Here's the sample MongoDB Doc:
(Quizzes have Questions; Questions have Answers)

{
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"}
]
}
],
}


When I was deleting an item that was nested a single level down (in this case, a question), I was able to do it with a query like:

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


(as described here: http://docs.mongodb.org/manual/core/update/#Updating-ModifierOperations , in the section titled "Update an Element without Specifying Its Position")

I tried expanding that to something like:

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


but didn't have any luck.

Any ideas would be greatly appreciated.

Answer

Use the positional operator in combination with $pull condition:

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

The above works to remove the second answer from the second question.