我正在使用mongo和laravel。
我通常在30天的时间内获取数据。我想按天分组数据。我已经尝试过$project
$dayOfMonth
并按day
分组,但是它按月的天数对它们进行分组,而我希望在此期间的天数内进行排序。
有办法吗?
[
'$match' => [
"created_at" => [
'$gte' => new \MongoDB\BSON\UTCDateTime($thisMonth),
]
],
],
[
'$project' => [
'day' => [
'$dayOfMonth' => [
'date' => '$created_at',
]
],
]
],
[
'$group' => [
'_id' => '$day',
'count' => ['$sum' => 1],
],
],
样本:
{#940
flag::STD_PROP_LIST: false
flag::ARRAY_AS_PROPS: true
iteratorClass: "ArrayIterator"
storage: array:16 [
"_id" => ObjectId {#933
+"oid": "5b2ff00e35826377be16ff82"
}
"orderNumber" => "10000"
"userName" => "dGFraHRlLTkwMDQ2NDcyOJRbugaZlHWdMR+nCNzaUfY="
"updated_at" => UTCDateTime {#938
+"milliseconds": "1529868539000"
}
"created_at" => UTCDateTime {#939
+"milliseconds": "1529868302000"
}
]
}
答案 0 :(得分:0)
您可以使用docs根据所需的格式将日期对象转换为字符串。
[ "$match" => [
"created_at" => [ '$gte' => new \MongoDB\BSON\UTCDateTime($thisMonth) ]
]],
[ "$group" => [
"_id" => [ "$dateToString" => [ "format" => "%Y-%m-%d", "date" => "$created_at" ] ],
"count" => [ "$sum" => 1 ]
]]