在php中我有以下mongo聚合功能:
array(
array(
'$match' => array(
"i" => array('$in' => $valRefId),
"date" => array('$gt'=> $mongotimestart , '$lte'=> $mongotimeend),
),
),
array(
'$project' => array(
"i" => '$i',
"v" => '$v',
"datumpje" => array('$add'=>array('$date',$timezone_date)),
"year" => array('$year' =>array('$add'=>array('$date',$timezone_date))),
"month" => array('$month'=>array('$add'=>array('$date',$timezone_date))),
"day" => array('$dayOfMonth'=>array('$add'=>array('$date',$timezone_date))),
"hour" => array('$hour'=> array('$add'=>array('$date',$timezone_date))),
)
),
array(
'$group' => array(
'_id' => array(
"valRefId" => '$i',
"year" => '$year',
"month" => '$month',
"day" => '$day',
"hour" => '$hour',
),
"MaxValue" => array('$max' => '$v'),
"MinValue" => array('$min' => '$v'),
"Gemiddelde" => array('$avg' => '$v'),
"Aantal" => array('$sum' => 1),
)
),
array(
'$sort' => array(
"_id.valRefId" => 1,
"_id.year" => 1,
"_id.month" => 1,
"_id.day" => 1,
"_id.hour" => 1,
)
),
array(
'$project' => array(
"date" => array(
'$concat' => array(array('$substr' => array('$_id.year',0,4)),
"-",
array('$substr' => array('$_id.month',0,2)),
"-",
array('$substr' => array('$_id.day',0,2)),
" ",
array('$substr' => array('$_id.hour',0,2)),
":00:00",
),
),
"MaxValue" => '$MaxValue',
"MinValue" => '$MinValue',
"Gemiddelde" => '$Gemiddelde',
"Aantal" => '$Aantal',
)
),
);
该函数的含义是获取一个时间窗口中的maxValue,MinValue,Average和记录数,其中 $i
在给定数组中( {{1} )然后按 $valRefId
, $i
, $year
,< strong> $month
和 $day
。
结果我现在有了“_id”。 “date”,“maxValue”,“minValue”,“Gemiddelde”,“Aantal”。
我现在的问题是,是否可以返回不是字符串类型的“日期”字段,而是返回日期类型(或时间戳类型)?
答案 0 :(得分:2)
是的,这是可能的。您可以使用 $group
累加器在$first
管道中返回日期字段,如下所示:
$pipeline = array(
array(
'$match' => array(
"i" => array('$in' => $valRefId),
"date" => array('$gt'=> $mongotimestart , '$lte'=> $mongotimeend),
),
),
array(
'$project' => array(
"i" => 1,
"v" => 1,
"datumpje" => array('$add'=>array('$date',$timezone_date)),
"year" => array('$year' =>array('$add'=>array('$date',$timezone_date))),
"month" => array('$month'=>array('$add'=>array('$date',$timezone_date))),
"day" => array('$dayOfMonth'=>array('$add'=>array('$date',$timezone_date))),
"hour" => array('$hour'=> array('$add'=>array('$date',$timezone_date))),
)
),
array(
'$group' => array(
'_id' => array(
"valRefId" => '$i',
"year" => '$year',
"month" => '$month',
"day" => '$day',
"hour" => '$hour',
),
"date" => array('$first' => '$datumpje'),
"MaxValue" => array('$max' => '$v'),
"MaxValue" => array('$max' => '$v'),
"MinValue" => array('$min' => '$v'),
"Gemiddelde" => array('$avg' => '$v'),
"Aantal" => array('$sum' => 1),
)
),
array(
'$sort' => array(
"_id.valRefId" => 1,
"_id.year" => 1,
"_id.month" => 1,
"_id.day" => 1,
"_id.hour" => 1,
)
)
);