You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 07:35:28