组结果中的MongoDB max [英] MongoDB max in group results
本文介绍了组结果中的MongoDB max的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将结果按 mvid
分组,并将每个组中出现的次数进行了计数。
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"}
])
显然,它会产生错误。我需要将max与group一起使用,但是我没有什么可以分组的。
It, obviously, generates an error. I need to use max with group, but I don't have anything to group on.
推荐答案
可行的方法是对结果进行排序,然后仅使用第一个元素:
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 }
])
与chridam的解决方案相比,我看到的优点是,您还可以得到具有最大数量的组的ID,但我希望它的速度较慢(未经测试)。
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).
这篇关于组结果中的MongoDB max的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文