How can I aggregate results by the highest count using aggregation framework?
{
"type": "dog",
"name": "buddy",
"count": 67
},
{
"type": "dog",
"name": "buddy",
"count": 34
},
{
"type": "dog",
"name": "tucker",
"count": 17
},
{
"type": "dog",
"name": "tucker",
"count": 52
},
{
"type": "cat",
"name": "gizmo",
"count": 11
}
I'm trying to aggregate the results from above, so if the dog has the same name I would like to get the one with the highest count. So it will look like:
{
"type": "dog",
"name": "buddy",
"count": 67
},
{
"type": "dog",
"name": "tucker",
"count": 52
},
{
"type": "cat",
"name": "gizmo",
"count": 11
}
I have tried using $group for that, but don't really know how I would distinct the results by the highest count.
Sort all the docs by count descending and then take first count from each grouping of type and name:
db.test.aggregate([
{$sort: {count: -1}},
{$group: {_id: {type: '$type', name: '$name'}, count: {$first: '$count'}}}
])
Output:
{
"result" : [
{
"_id" : {
"type" : "cat",
"name" : "gizmo"
},
"count" : 11
},
{
"_id" : {
"type" : "dog",
"name" : "tucker"
},
"count" : 52
},
{
"_id" : {
"type" : "dog",
"name" : "buddy"
},
"count" : 67
}
],
"ok" : 1
}