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

Laravel中MongoDB按created_at年份分组查询及记录数统计

在Laravel中对MongoDB的customer集合按年份分组统计记录数

嘿,要实现这个需求其实很简单——前提是你已经用上了jenssegers/laravel-mongodb这个主流的MongoDB扩展包(毕竟Laravel原生不直接支持MongoDB操作)。下面给你两种实用的实现方式:

方式一:使用MongoDB原生聚合管道(最稳妥)

这种方式直接调用MongoDB的聚合语法,兼容性最好,适合所有版本的扩展包。首先确保你的Customer模型已经关联了MongoDB连接(模型里设置$connection = 'mongodb',$collection = 'customer'),然后用raw方法执行聚合:

use App\Models\Customer;

$yearlyStats = Customer::raw(function ($collection) {
    return $collection->aggregate([
        // 按created_at的年份分组,统计数量
        [
            '$group' => [
                '_id' => ['year' => ['$year' => '$created_at']], // 提取年份作为分组ID
                'total_records' => ['$sum' => 1] // 统计每组的记录数
            ]
        ],
        // 可选:按年份升序排序,让结果更清晰
        [
            '$sort' => ['_id.year' => 1]
        ]
    ]);
});

// 遍历输出结果
foreach ($yearlyStats as $stat) {
    echo "年份:{$stat['_id']['year']},总记录数:{$stat['total_records']}\n";
}

方式二:使用Eloquent查询构建器(简化写法)

如果你习惯Laravel的链式查询风格,扩展包也支持用selectRaw和groupBy来实现,写法更贴近原生Eloquent:

use App\Models\Customer;
use Illuminate\Support\Facades\DB;

$yearlyStats = Customer::selectRaw(['$year(created_at) as year', DB::raw('count(*) as total_records')])
    ->groupBy('year')
    ->orderBy('year', 'asc')
    ->get();

// 输出结果示例
foreach ($yearlyStats as $stat) {
    echo "年份:{$stat->year},总记录数:{$stat->total_records}\n";
}

重要注意事项

  • 确保created_at字段类型正确:必须是MongoDB的Date类型,而不是字符串。如果你的created_at是字符串格式,需要先转换为Date类型再提取年份,修改聚合管道如下:
    $yearlyStats = Customer::raw(function ($collection) {
        return $collection->aggregate([
            [
                '$addFields' => [
                    'created_at_date' => ['$toDate' => '$created_at'] // 把字符串转成Date
                ]
            ],
            [
                '$group' => [
                    '_id' => ['year' => ['$year' => '$created_at_date']],
                    'total_records' => ['$sum' => 1]
                ]
            ]
        ]);
    });
    
  • 版本兼容性:如果使用的是较旧版本的jenssegers/laravel-mongodb,链式查询的写法可能存在兼容性问题,此时优先选择聚合管道的方式更可靠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:30:04