如何在 laravel MongoDB 中使用 groupBy Month 和 Sum

How to use groupBy Month and Sum in laravel MongoDB

查询以获取每月订单(每月总订单数(count)或每月总销售额(sum)): 试过这个查询,但它不工作。还尝试使用 Whosebug 的其他结果,但我不明白 MongoDB 查询是如何完成的。这是那个问题的link:select-sum-column-and-group-by-with-mongodb-and-laravel

$monthly_orders = Order::select(
    DB::raw('sum(total_amount) as sum'),
    DB::raw('YEAR(created_at) year, MONTH(created_at) month'),
)
->groupBy('month')
->get();

当我尝试使用按客户 ID 分组来获取总金额时,它返回的总和为 null

$monthly_orders = Order::selectRaw('sum(total_amount) as sum, customer_id')
    ->groupBy('customer_id')
    ->pluck('sum', 'customer_id');

结果:

Illuminate\Support\Collection {#2123 ▼
  #items: array:4 [▼
    "6098e5ff5977a25ee96a2a42" => null
    "60dbf87f7d8ffb7cdb2233d2" => null
    "605af409195d8e59e34893f2" => null
    "60ddae4a66fb69678e45f056" => null
  ]
}

尝试使用 rawaggregate

$monthly_orders = Order::raw(function ($collection) {
        return $collection->aggregate([
            [
                '$group' => [
                    "_id" => '$customer_id',
                    'customer_id' => ['$first' => '$customer_id'],
                    'sum' => ['$sum' => '$total_amount']
                ]
            ],

        ]);
    });

你可以使用 pluck

$monthly_orders->pluck('sum','customer_id')

按月分组

 $monthly_orders = Order::raw(function ($collection) {
            return $collection->aggregate([
                [
                    '$group' => [
                       "_id" => ['$month'=>'$created_at'],
                        'customer_id' => ['$first' => '$customer_id'],
                        'sum' => ['$sum' => '$total_amount']
                    ]
                ],
    
            ]);
        });