Given this MongoDB collection:
[
{ character: 'broquaint', race: 'Halfling', class: 'Hunter' },
{ character: 'broquaint', race: 'Halfling', class: 'Hunter' },
{ character: 'broquaint', race: 'Halfling', class: 'Rogue' },
{ character: 'broquaint', race: 'Naga', class: 'Fighter' },
{ character: 'broquaint', race: 'Naga', class: 'Hunter' }
]
I would like to get a count of each race and class i.e
{
race: { 'Halfling': 3, 'Naga': 2 },
class: { 'Hunter': 3, 'Rogue': 1, 'Fighter': 1 }
}
And I've been trying to do this using the aggregation framework (to replace an existing map/reduce) but have only been able to get as far as getting counts for the combinations i.e
{ '_id': { race: 'Halfling', class: 'Hunter' }, count: 2 }
{ '_id': { race: 'Halfling', class: 'Rogue' } count: 1 }
{ '_id': { race: 'Naga', class: 'Fighter' }, count: 1 }
{ '_id': { race: 'Naga', class: 'Hunter' }, count: 1 }
Which is simple enough to reduce programmatically to the desired result but I was hoping to be able to leave that to MongoDB.
For reference here's the code I have so far:
db.games.aggregate(
{ '$match': { character: 'broquaint' } },
{
'$group': {
_id: { race: '$race', background: '$background'},
count: { '$sum': 1 }
}
}
)
So the question is - given that example collection can I arrive at my desired output purely through MongoDB's aggregation framework?
For any help that might be rendered many thanks in advance!