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
There are a few ways to approach this depending on how much data you need to process. You could use the Aggregation Framework in MongoDB 2.2+, or possibly Map/Reduce. See Aggregation Commands Comparison for a summary of the features and limitations.
Here's an example using the Aggregation Framework:
db.fruit.aggregate(
// Limit matching documents (can take advantage of index)
{ $match: {
"_id" : ObjectId("52c1d909fc7fc68ffffd999a73")
}},
// Unpack the question & answer arrays
{ $unwind: "$questions" },
{ $unwind: "$questions.answers" },
// Group by the answer values
{ $group: {
_id: "$questions.answers.answer",
count: { $sum: 1 }
}}
)
For your sample document this returns:
{
"result" : [
{
"_id" : "banana",
"count" : 1
},
{
"_id" : "apple",
"count" : 2
}
],
"ok" : 1
}