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

如何在MongoDB中同时查询按日期分组的消费总和及全量总消费额

你可以使用MongoDB聚合框架的$facet阶段实现需求,仅需一次集合扫描即可同时完成按日期统计单日消费、计算全集合总消费两个任务,再合并结果即可。

具体查询代码

db.billow.aggregate([
  // 并行执行两个统计分支
  {
    $facet: {
      // 分支1:统计每日消费总额
      dailyStats: [
        {
          $group: {
            _id: "$date",
            cost: { $sum: "$cost" }
          }
        },
        {
          $project: {
            _id: 0,
            day: "$_id",
            cost: 1
          }
        }
      ],
      // 分支2:统计全集合总消费额
      totalCost: [
        {
          $group: {
            _id: null,
            total: { $sum: "$cost" }
          }
        },
        { $project: { _id: 0 } }
      ]
    }
  },
  // 拆分每日统计数组为独立文档
  { $unwind: "$dailyStats" },
  // 给每个每日统计附加全局总金额
  {
    $addFields: {
      "dailyStats.total": { $first: "$totalCost.total" }
    }
  },
  // 调整输出为目标格式
  { $replaceRoot: { newRoot: "$dailyStats" } }
])

输出结果

对应你提供的示例数据,查询输出如下:

[
  {
    "day": "12-2-2015",
    "cost": 140,
    "total": 260
  },
  {
    "day": "13-2-2015",
    "cost": 120,
    "total": 260
  }
]

逻辑说明

  • $facet支持在同一份输入数据上运行多个独立的聚合分支,无需多次扫描集合,性能更高
  • 拿到两个分支的统计结果后,将每日统计数组拆分为独立文档,再把全局总金额附加到每个文档上
  • 最后通过$replaceRoot调整文档结构,完全匹配你需要的输出格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 04:57:03