我知道mongoDB(php-driver)将日期保存为以毫秒UTC为单位的ISODate,因此我必须为我的时区(GMT +2:00)添加一个偏移到聚合查询。
$dateStart = new MongoDB\BSON\UTCDateTime(strtotime("now 00:00:00") * 1000);
$dateEnd = new MongoDB\BSON\UTCDateTime(time() * 1000);
$queryHours = [
['$match' => ['date' => ['$gte' => $dateStart, '$lte' => $dateEnd]]],
['$project' => ['date' => ['$add' => ['$date', 2*60*60000]]]],
['$group' => ['_id' => ['$hour' => '$date'], 'average' => ['$avg' => '$zapi.apiRes.curlHeader.total_time']]],
['$sort' => ['_id' => 1]],
];
$ hour结果似乎是正确的,但我没有得到“平均”结果,我几天都没有看到我的失败,盯着代码。 :(
示例文档:
{
"_id" : ObjectId("58e4e3ca135d9e038242b248"),
"date" : ISODate("2017-04-05T12:32:10Z"),
[...]
"zapi" : {
"apiRes" : {
"apiCall" : {
[...]
},
"curlHeader" : {
"url" : "http://api:/api/foo",
"http_code" : 204,
"total_time" : 0.02906399999999998,
[...]
},
}
},
}
我知道mongoDB正在使用这个功能:https://jira.mongodb.org/browse/SERVER-28611。
谢谢和最诚挚的问候,
lun4tic
答案 0 :(得分:1)
您的错误应该是项目阶段。您必须添加'zapi.apiRes.curlHeader.total_time' => 1
,请尝试以下操作:
$queryHours = [
['$match' => ['date' => ['$gte' => $dateStart, '$lte' => $dateEnd]]],
['$project' => ['date' => ['$add' => ['$date', 2*60*60000]], 'zapi.apiRes.curlHeader.total_time' => 1]],
['$group' => ['_id' => ['$hour' => '$date'], 'average' => ['$avg' => '$zapi.apiRes.curlHeader.total_time']]],
['$sort' => ['_id' => 1]],
];
答案 1 :(得分:1)
如果您使用的是3.4版本,则可以将$project
阶段替换为$addFields
。
$queryHours =
[
['$match' => ['date' => ['$gte' => $dateStart, '$lte' => $dateEnd]]],
['$addFields' => ['date' => ['$add' => ['$date', 2*60*60000]]]],
['$group' => ['_id' => ['$hour' => '$date'], 'average' => ['$avg' => '$zapi.apiRes.curlHeader.total_time']]],
['$sort' => ['_id' => 1]],
];
或
您只需将时区算术从$project
阶段移至$group
阶段即可。
['$group' => ['_id' => ['$hour' => [ '$add' => ['$date', 2*60*60000] ] ], 'average' => ['$avg' => '$zapi.apiRes.curlHeader.total_time']]],