我在laravel中使用mongodb,但是在某些时候我卡住了。我想获取大于created_at
的数据计数,并且还要按天created_at
分组。我也想获取另一个按device_type
分组的计数。请帮我。下面是我的代码。 $time:2019-06-01 00:00:00
Documents :
{ "_id" : ObjectId("5cf8b42136cbc8d0e2aad747"), "user_id" : 50146, "device_type" : 1, "created_at" : ISODate("2019-06-06T06:35:13.828Z") }
{ "_id" : ObjectId("5cf8b90f36cbc8d0e2aad749"), "user_id" : 50146, "device_type" : 1, "created_at" : ISODate("2019-06-06T06:56:15.046Z") }
{ "_id" : ObjectId("5cf8b91136cbc8d0e2aad74b"), "user_id" : 73854, "device_type" : 2, "created_at" : ISODate("2019-06-04T06:56:17.926Z") }
{ "_id" : ObjectId("5cf8b91536cbc8d0e2aad74d"), "user_id" : 73854, "device_type" : 2, "created_at" : ISODate("2019-06-03T06:56:21.595Z") }
{ "_id" : ObjectId("5cf8d0af36cbc8d0e2aad74f"), "user_id" : 50146, "device_type" : 1, "created_at" : ISODate("2019-05-31T08:37:03.454Z") }
{ "_id" : ObjectId("5cf8d0b236cbc8d0e2aad751"), "user_id" : 73854, "device_type" : 2, "created_at" : ISODate("2019-06-01T08:37:06.627Z") }
{ "_id" : ObjectId("5cf8d0b436cbc8d0e2aad753"), "user_id" : 73854, "device_type" : 2, "created_at" : ISODate("2019-06-02T08:37:08.786Z") }
MongoQuery :
UserSession::raw(function ($collection) use ($time) {
return $collection->aggregate([
['$match' => [
"created_at" => ['$gte' => new \MongoDB\BSON\UTCDateTime($time)]
]],
['$group' => [
"_id" => ['$dateToString' => ["format" => "%Y-%m-%d", "date" => '$created_at']],
"count" => ['$sum' => 1]
]],
[
'$sort' => ['_id' => 1]
],
]);
});
这只是给我created_at
分组的计数。我还想要另一个device_type
分组的计数,我在这里感到困惑。请帮我。任何帮助将不胜感激。