按最高计数汇总

时间:2014-07-24 14:08:55

标签: javascript node.js mongodb 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
}

我正在尝试汇总上面的结果,因此如果dog具有相同的name,我希望获得具有最高计数的结果。所以它看起来像:

{
  "type": "dog",
  "name": "buddy",
  "count": 67
},
{
  "type": "dog",
  "name": "tucker",
  "count": 52
},
{
  "type": "cat",
  "name": "gizmo",
  "count": 11
}

我已尝试使用$group,但我不知道如何以最高计数区分结果。

1 个答案:

答案 0 :(得分:3)

count降序排序所有文档,然后从counttype的每个分组中获取第一个name

db.test.aggregate([
    {$sort: {count: -1}},
    {$group: {_id: {type: '$type', name: '$name'}, count: {$first: '$count'}}}
])

输出:

{
    "result" : [ 
        {
            "_id" : {
                "type" : "cat",
                "name" : "gizmo"
            },
            "count" : 11
        }, 
        {
            "_id" : {
                "type" : "dog",
                "name" : "tucker"
            },
            "count" : 52
        }, 
        {
            "_id" : {
                "type" : "dog",
                "name" : "buddy"
            },
            "count" : 67
        }
    ],
    "ok" : 1
}