I have a collection that contains documents with a structure like below:
{
answers: [
{
Title: 'What's your age?',
values: [
{value: true, label: '18-30'}
]
},
{
Title: 'What's your favorite color(s)?',
values: [
{value: true, label: 'Red'},
{value: true, label: 'Green'}
]
}
]
},
{
answers: [
{
Title: 'What's your age?',
values: [
{value: true, label: '31-40'}
]
},
{
Title: 'What's your favorite color(s)?',
values: [
{value: true, label: 'Red'}
]
}
]
}
I'd like to get the counts for the various answers. So for the above data I'd like to get something like:
{
{
Title: "What's your age?",
AgeTotals: {
"18-30": 1,
"31-40": 1
}
},
{
Title: "What's your favorite color(s)?",
ColorTotals: {
"Red": 2,
"Green": 1
}
}
}
My first thought was to do something like this:
db.test.aggregate(
{$unwind: "$answers"},
{$unwind: "$answers.values"},
{$group:{
_id: "$answers.values.label",
totals: {$sum: 1}
}
}
);
But this generates the output:
{ "_id" : "31-40", "totals" : 1 }
{ "_id" : "Red", "totals" : 2 }
{ "_id" : "Green", "totals" : 1 }
{ "_id" : "18-30", "totals" : 1 }
How would I go about getting the totals for each answer rather than the above?
UPDATE:
Alternatively I would be ok if the data were output in the following format:
{ "title: "What's your age?", "_id" : "31-40", "totals" : 1 }
{ "title": "What's your favorite color?", "_id" : "Red", "totals" : 2 }
{ "title": "What's your favorite color?", "_id" : "Green", "totals" : 1 }
{ "title: "What's your age?", "_id" : "18-30", "totals" : 1 }