问题
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