MongoDB max in group results

好久不见. 提交于 2020-01-03 01:40:28

问题


I grouped results by mvid and the counted number of occurrences in each group.

db.some_details.aggregate([
{$group: {_id: "$mvid", count: {$sum: 1}}}
])

Now, I would like to select group with max count. Here is my naive guess:

db.some_details.aggregate([
{$group: {_id: "$mvid", count: {$sum: 1}}},
{$max: "count"}
])

It, obviously, generates an error. I need to use max with group, but I don't have anything to group on.


回答1:


What also would work is sorting the result and then using only the first element:

db.some_details.aggregate([
{$group: {_id: "$mvid", count: {$sum: 1}}},
{$sort: {"count": -1}},
{$limit: 1 }
])

The advantage that I see compared to chridam's solution is that you also get the id of the group with the maximum count, but I expect it to be slower (not tested).




回答2:


The aggregation pipeline allows you to could include another $group operator pipeline that would give you the maximum count of all the groups:

db.some_details.aggregate([
    {
        $group: {
            _id: "$mvid", 
            count: { $sum: 1 }
        }
    },
    {
        $group: {
            _id: 0, 
            maxCount: { $max: "$count" }
        }
    }
])


来源:https://stackoverflow.com/questions/31056647/mongodb-max-in-group-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!