如何在MongoDB聚合查询中仅返回销量最高的商品?
获取MongoDB中销量最高的商品的查询修改方案
你的聚合查询已经完成了商品销量的统计与降序排序,要仅返回销量最高的那一项,最直接的方式是在管道末尾添加$limit阶段:
修改后的查询语句
db.sales.aggregate( [ { $unwind : "$detail" }, { $project : { "name" : "$detail.name" } }, { $group: { _id: "$name", quantity: { $sum: 1 } } }, { $sort: { quantity: -1 } }, // 新增:仅返回排序后的第一个文档 { $limit: 1 } ] );
说明
$limit: 1会截取排序后的第一个结果,也就是销量最高的商品,返回结果类似:
[ { "_id": "Producto 2", "quantity": 38 } ]
扩展:处理多个销量并列最高的情况
如果存在多个商品销量同为最高值,上述$limit只会返回其中一个。若要返回所有销量最高的商品,可以用以下方案:
db.sales.aggregate([ { $unwind: "$detail" }, { $project: { "name": "$detail.name" } }, { $group: { _id: "$name", quantity: { $sum: 1 } } }, // 先收集所有统计结果并记录最大销量 { $group: { _id: null, maxQuantity: { $max: "$quantity" }, productList: { $push: "$$ROOT" } } }, // 展开商品列表并筛选出销量等于最大值的项 { $unwind: "$productList" }, { $match: { "productList.quantity": "$maxQuantity" } }, // 恢复原文档格式 { $replaceRoot: { newRoot: "$productList" } } ])
这个方案会先统计出最高销量值,再筛选出所有销量等于该值的商品,确保不会遗漏并列第一的项。
内容的提问来源于stack exchange,提问作者OscarDev
相关产品推荐
相关产品推荐

