mongodb-获得按字段分组的总和的最大值 [英] mongodb - get highest value of a sum groupped by a field
本文介绍了mongodb-获得按字段分组的总和的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想我们有此数据
{ "_id" : 1, "item" : "abc", "quantity" : 2, "category" : 1}
{ "_id" : 2, "item" : "jkl", "quantity" : 1, "category" : 1}
{ "_id" : 3, "item" : "xyz", "quantity" : 5, "category" : 2}
{ "_id" : 4, "item" : "abc", "quantity" : 10, "category" : 2}
{ "_id" : 5, "item" : "xyz", "quantity" : 10, "category" : 3}
{ "_id" : 6, "item" : "cds", "quantity" : 9, "category" : 3}
我要查询一个包含最大数量的类别。
,所以我必须:
i want to make a query that give me the category that contain the biggest quantity. so i have to:
1-按类别分组
2-求和每个类别中的项目数量
2- make the sum of quantities of items in each category
3-在这些总和中获得最高价值。
3- get the highest value among those sums.
请帮助我进行此查询。
预先感谢
Please help me to make this query. Thank you in advance
推荐答案
在 $ sort
中使用 $ limit
以获取最大总数:
Use $sort
with $limit
to get the maximum total:
db.items.aggregate([
{ $match: {} },
{ $group: {
_id: '$category',
sumQ: {$sum: '$quantity'}
}
},
{ $sort: {sumQ: -1 } },
{ $limit: 1 }
])
这篇关于mongodb-获得按字段分组的总和的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文