如何使用聚合以及group by和sum

时间:2018-01-23 13:51:18

标签: mongodb laravel aggregation-framework

如何使用price字段按周,日,年分别获得已购买交易purchased_at(当前年度数据)组的总和

我的收集数据:

{
"_id": ObjectId("5a66d619042e9f3a070d6864"),
"name": "Deal1",
"price": "2000",
"status": true,
"purchased_at": ISODate("2018-01-23T06:28:41.0Z")
}
{
"_id": ObjectId("5a66d619042e9f3a070d6872"),
"name": "Deal2",
"price": "500",
"status": true,
"purchased_at": ISODate("2018-01-13T06:28:41.0Z")
}
{
"_id": ObjectId("5a66d619042e9f3a070d6880"),
"name": "Deal3",
"price": "1000",
"status": true,
"purchased_at": ISODate("2018-02-13T06:28:41.0Z")
}
{
"_id": ObjectId("5a66d619042e9f3a070d6880"),
"name": "Deal4",
"price": "1000",
"status": false,
"purchased_at": ISODate("2018-01-11T06:28:41.0Z")
}

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

由于您使用的是非标准日期格式,因此需要使用filter()

$lastWeekSum = $collection->filter(function($i) {
    Carbon::parse($i['purchased_at'])->gt(now()->subWeek());
})->sum('price');

如果$i['purchased_at']返回一个对象,则应在解析之前将其转换为2018-01-11T06:28:41.0Z之类的字符串。