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

如何获取卖家订单并按日期排序,修复月度销售额统计返回空数组问题

问题修复:MongoDB聚合查询返回空数组及需求实现

需求说明

获取指定卖家的所有订单并按从过去到现在的日期排序,同时统计该卖家每月的销售总额(示例中10月总额100,11月总额120)。

现有问题

当前路由代码执行聚合查询时返回空数组,核心问题如下:

  • 匹配卖家ID时字段错误:$elemMatch中误用了id,实际订单数据里的卖家字段是sellerId
  • 不必要的日期过滤:原代码限制createdAt >= previousMonth,若当前日期远晚于订单创建日期(示例订单为2022年),会直接过滤掉所有历史订单
  • 未实现订单排序需求
  • 聚合结果仅返回月份数字,未转换为期望的月份名称

修正后的代码

router.get('/previousSales/:id', async (req, res) => {
    const { id } = req.params;

    try {
        const aggregatedData = await Order.aggregate([
            // 匹配包含指定卖家ID的订单
            {
                $match: {
                    "products.sellerId": id
                }
            },
            // 提取月份、订单金额及原订单信息
            {
                $project: {
                    month: { $month: "$createdAt" },
                    sales: "$amount",
                    createdAt: 1,
                    products: 1,
                    amount: 1
                }
            },
            // 按月份分组统计销售总额,同时保留该月份的所有订单
            {
                $group: {
                    _id: "$month",
                    total: { $sum: "$sales" },
                    orders: { $push: "$$ROOT" }
                }
            },
            // 将月份数字转换为英文名称
            {
                $addFields: {
                    monthName: {
                        $switch: {
                            branches: [
                                { case: { $eq: ["$_id", 1] }, then: "January" },
                                { case: { $eq: ["$_id", 2] }, then: "February" },
                                { case: { $eq: ["$_id", 3] }, then: "March" },
                                { case: { $eq: ["$_id", 4] }, then: "April" },
                                { case: { $eq: ["$_id", 5] }, then: "May" },
                                { case: { $eq: ["$_id", 6] }, then: "June" },
                                { case: { $eq: ["$_id", 7] }, then: "July" },
                                { case: { $eq: ["$_id", 8] }, then: "August" },
                                { case: { $eq: ["$_id", 9] }, then: "September" },
                                { case: { $eq: ["$_id", 10] }, then: "October" },
                                { case: { $eq: ["$_id", 11] }, then: "November" },
                                { case: { $eq: ["$_id", 12] }, then: "December" }
                            ],
                            default: "Unknown"
                        }
                    }
                }
            },
            // 按月份从早到晚排序
            {
                $sort: { _id: 1 }
            },
            // 整理输出格式,同时将每个月的订单按创建时间从过去到现在排序
            {
                $project: {
                    _id: 0,
                    monthName: 1,
                    total: 1,
                    orders: { $sortArray: { input: "$orders", sortBy: { createdAt: 1 } } }
                }
            }
        ]);

        // 转换为期望的文本格式输出
        const formattedOutput = aggregatedData.map(item => `${item.monthName} = ${item.total}`).join('\n');
        res.status(200).send(formattedOutput);
        // 若需返回JSON格式,替换为:res.status(200).json(aggregatedData);
    } catch (error) {
        res.status(400).json({ message: error.message });
    }
});

关键修复点

  • 卖家ID匹配修正:将错误的products: {$elemMatch: {id}}改为"products.sellerId": id,直接匹配数组中的卖家ID字段,简洁高效
  • 移除错误日期过滤:删除createdAt: {gte: previousMonth},确保能获取该卖家的所有历史订单
  • 添加排序逻辑:通过$sort按月份排序,同时用$sortArray将每个月份下的订单按创建时间从过去到现在排序
  • 月份名称转换:使用$switch将月份数字映射为英文名称,匹配期望输出格式

输出结果

针对示例数据,执行修正后的代码将返回:

October = 100
November = 120

内容的提问来源于stack exchange,提问作者Stykgwar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 09:20:36