You need to enable JavaScript to run this app. 如何用Mongoose实现MongoDB订单的日/周/月销售额计算(支持特定卖家)
优惠活动
大模型
产品
解决方案
定价
更多

如何用Mongoose实现MongoDB订单的日/周/月销售额计算(支持特定卖家)

统计实现方案

所有计算通过Mongoose聚合管道完成,直接在MongoDB服务端完成分组求和,避免应用层拉取全量订单数据造成的性能损耗,同时天然支持全局统计、指定卖家维度统计两种场景,输出结构适配前端图表渲染要求。

前置统一规则
  • 统计口径:默认以订单实际支付时间paidAt为时间基准,仅筛选isPaid = true且paidAt字段存在的有效订单,未支付订单不计入销售额
  • 维度适配:全局统计不设置额外过滤条件;卖家侧统计需追加匹配条件,仅保留seller字段为指定卖家ID的订单
  • 输出兼容:聚合结果统一按时间升序排列,附带订单量统计字段,可直接绑定折线图、柱状图组件
分周期统计代码实现

所有实现为通用函数,调用时传入卖家ID即可返回对应卖家的周期数据,传空则返回全平台统计数据。

每日销售额统计

import mongoose from 'mongoose';
import Order from './your-order-model-path.js';

async function getDailySales(sellerId = null) {
  // 基础匹配条件
  const matchFilter = {
    isPaid: true,
    paidAt: { $exists: true }
  };
  // 传入卖家ID时追加维度过滤
  if (sellerId) {
    matchFilter.seller = new mongoose.Types.ObjectId(sellerId);
  }

  return Order.aggregate([
    { $match: matchFilter },
    {
      $group: {
        _id: {
          // 按自然日截断时间分组
          day: { $dateTrunc: { date: "$paidAt", unit: "day" } }
        },
        totalSales: { $sum: "$totalPrice" },
        orderCount: { $sum: 1 }
      }
    },
    // 按日期升序排列,适配图表X轴顺序
    { $sort: { "_id.day": 1 } },
    // 重构输出结构,去除冗余的_id嵌套字段
    {
      $project: {
        _id: 0,
        date: "$_id.day",
        totalSales: 1,
        orderCount: 1
      }
    }
  ]);
}

每周销售额统计

async function getWeeklySales(sellerId = null) {
  const matchFilter = {
    isPaid: true,
    paidAt: { $exists: true }
  };
  if (sellerId) {
    matchFilter.seller = new mongoose.Types.ObjectId(sellerId);
  }

  return Order.aggregate([
    { $match: matchFilter },
    {
      $group: {
        _id: {
          week: {
            $dateTrunc: {
              date: "$paidAt",
              unit: "week",
              weekStart: 1 // 配置周起始日:1=周一,7=周日,适配国内统计习惯
            }
          }
        },
        totalSales: { $sum: "$totalPrice" },
        orderCount: { $sum: 1 }
      }
    },
    { $sort: { "_id.week": 1 } },
    {
      $project: {
        _id: 0,
        weekStartDate: "$_id.week",
        totalSales: 1,
        orderCount: 1
      }
    }
  ]);
}

每月销售额统计

async function getMonthlySales(sellerId = null) {
  const matchFilter = {
    isPaid: true,
    paidAt: { $exists: true }
  };
  if (sellerId) {
    matchFilter.seller = new mongoose.Types.ObjectId(sellerId);
  }

  return Order.aggregate([
    { $match: matchFilter },
    {
      $group: {
        _id: {
          month: { $dateTrunc: { date: "$paidAt", unit: "month" } }
        },
        totalSales: { $sum: "$totalPrice" },
        orderCount: { $sum: 1 }
      }
    },
    { $sort: { "_id.month": 1 } },
    {
      $project: {
        _id: 0,
        month: "$_id.month",
        totalSales: 1,
        orderCount: 1
      }
    }
  ]);
}
落地注意事项
  • 性能优化:在Schema层面创建联合索引,大幅降低大订单量下的聚合查询耗时:
    // 建议追加到orderSchema定义中
    orderSchema.index({ isPaid: 1, paidAt: 1, seller: 1 });
    
  • 旧版本兼容:如果使用MongoDB 5.0以下版本,不支持$dateTrunc操作,可替换为$dateToString实现日期分组,例如按日分组时将分组键改为{ day: { $dateToString: { format: "%Y-%m-%d", date: "$paidAt" } } },统计效果一致。
  • 口径灵活调整:
    • 如果需要按订单创建时间(而非支付时间)统计,将聚合管道中所有$paidAt替换为Schema自动生成的createdAt字段即可
    • 如果需要仅统计商品销售收入(剔除运费、税费),将聚合中的求和字段从$totalPrice替换为$itemsPrice即可
  • 图表适配:聚合管道仅会返回存在有效订单的周期,某个周期无订单时不会生成对应数据条目,前端渲染图表时需要自动补全空周期的零值,避免折线图、柱状图出现断点。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 09:36:04