How to count occurrences in nested document in mongodb?

Viewed 6712

In the situation where there is an array nested within an array, how would I count the number of a specific value? For example, I want to count the number of "answers" in the document below. query should return that there are 2 apples and 1 banana.

{
  "_id" : ObjectId("52c1d909fc7fc68ddd999a73"),
  "name" : "Some survey",
  "questions" : [
    {
      "_id" : ObjectId("52c1e250fc7fc68ddd999a75"),
      "answers" :
      [
        {
          "userId" : "some GUIDs",
          "answer" : "apple"
        },
        {
          "userId" : "some GUID",
          "answer" : "apple"
        },
        {
          "userId" : "some GUID",
          "answer" : "banana"
        }
      ],
      "questionText" : "blah blah blah...",
      "questionType" : "multiple choice"
    }
]

}

2 Answers
Related