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

如何在Prisma中对MongoDB订单按月份分组并求和?

解决Prisma+MongoDB按月份统计订单总额的问题

你的原代码是按createdAt的完整日期分组,得到的是每天的总额,而非每月的。Prisma的groupBy目前不支持直接对日期字段提取月份进行分组,因此需要通过以下两种方式实现需求:

方法一:MongoDB聚合管道(数据库层面处理,适合大数据量)

通过Prisma执行MongoDB原生聚合操作,直接在数据库中按月份分组求和:

// 执行聚合查询
const aggregateResult = await prisma.$runCommand({
  aggregate: "orders",
  pipeline: [
    {
      $group: {
        _id: { $month: "$createdAt" }, // 提取月份数字(1=1月,12=12月)
        totalAmount: { $sum: "$totalAmount" } // 统计当月总额
      }
    },
    { $sort: { _id: 1 } } // 按月份顺序排序
  ],
  cursor: {}
});

// 转换为目标格式
const monthNames = [
  "january", "february", "march", "april", "may", "june",
  "july", "august", "september", "october", "november", "december"
];

const salesByMonth = aggregateResult.cursor.firstBatch.reduce((acc, item) => {
  const monthName = monthNames[item._id - 1]; // 转换为月份名称
  acc[monthName] = item.totalAmount;
  return acc;
}, {});

console.log(salesByMonth);

方法二:客户端侧分组处理(适合小数据量)

先查询所有订单数据,再在JavaScript中按月份分组求和:

// 查询所有订单的日期和金额
const allOrders = await prisma.orders.findMany({
  select: {
    createdAt: true,
    totalAmount: true
  }
});

// 转换为目标格式
const monthNames = [
  "january", "february", "march", "april", "may", "june",
  "july", "august", "september", "october", "november", "december"
];

const salesByMonth = allOrders.reduce((acc, order) => {
  const monthIndex = order.createdAt.getMonth(); // 0=1月,11=12月
  const monthName = monthNames[monthIndex];
  acc[monthName] = (acc[monthName] || 0) + order.totalAmount;
  return acc;
}, {});

console.log(salesByMonth);

注意事项

  • 数据量较大时优先使用方法一,避免大量数据传输到客户端影响性能
  • 可根据需求调整monthNames中的月份名称大小写(比如改为首字母大写)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 01:12:55