You need to enable JavaScript to run this app. 如何在Laravel MongoDB中实现按月分组聚合及求和操作
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel MongoDB中实现按月分组聚合及求和操作

MongoDB + Laravel 分组统计实现方案

你当前使用的SQL风格查询语法仅适用于MySQL等关系型数据库,Laravel MongoDB扩展不支持YEAR()、MONTH()这类SQL函数,也无法直接通过selectRaw实现sum聚合,所以会出现执行报错、sum返回null的问题,正确实现方式如下:

场景1:按月度统计订单总数、销售总额

通过MongoDB聚合管道实现:

$monthlyStats = Order::raw(function($collection) {
    return $collection->aggregate([
        // 提取年月、保留订单金额字段
        [
            '$project' => [
                'year' => ['$year' => '$created_at'],
                'month' => ['$month' => '$created_at'],
                'total_amount' => 1
            ]
        ],
        // 按年月分组统计
        [
            '$group' => [
                '_id' => ['year' => '$year', 'month' => '$month'],
                'order_count' => ['$sum' => 1], // 当月订单总数
                'total_sales' => ['$sum' => '$total_amount'] // 当月销售总额
            ]
        ],
        // 按时间倒序排序,可选
        [
            '$sort' => ['_id.year' => -1, '_id.month' => -1]
        ]
    ]);
});

返回结果中_id字段包含统计的年份和月份,order_count为对应月度订单总数,total_sales为对应月度销售总额。

场景2:按customer_id统计客户总消费金额

$customerConsumption = Order::raw(function($collection) {
    return $collection->aggregate([
        [
            '$group' => [
                '_id' => '$customer_id',
                'total_amount' => ['$sum' => '$total_amount']
            ]
        ]
    ]);
})->pluck('total_amount', '_id');

返回结果为以customer_id为键、客户总消费金额为值的集合,和你预期的pluck输出结构一致。

注意事项

  • 请确保total_amount字段为数值类型(int/float),若存储为字符串会导致sum计算异常
  • 请确保created_at字段为MongoDB原生ISODate类型,若为字符串格式时间需要先做类型转换才能使用$year、$month运算符

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 16:21:03