我想合并两个集合,并按外部表中的日期字段进行排序,然后对字段进行分组,以获取每个设备最近日期的一条记录,如下所示。
我需要以下结果。
$collection = $this->db->dv_device;
$result_data = $collection->aggregate(
array('$lookup'=>array('from'=>'dv_device_readings', 'localField'=>'device_id', 'foreignField'=>'device_id','as'=>'result_data')),
array('$match'=>array('user_id'=>'5809c169622d10a419000029')),
array('$sort'=>array('result_data.date_time'=>-1)),
array('$group' => array(
"_id" => array("device_id" => '$result_data.device_id'),
"device_id" => array('$first' => '$result_data.device_id'),
"date_time" => array('$first' => '$result_data.date_time'),
"dc_voltage" => array('$first' => '$result_data.dc_voltage'),
"dc_current" => array('$first' => '$result_data.dc_current'),
"output_voltage" => array('$first' => '$result_data.output_voltage'),
"output_current" => array('$first' => '$result_data.output_current'),
))
);
使用以上PHP代码,我得到了以下结果,合并两个集合运行良好,但排序和分组不起作用。
Array
(
[waitedMS] => 0
[result] => Array
(
[0] => Array
(
[_id] => Array
(
[device_id] => Array
(
[0] => dv1002
[1] => dv1002
)
)
[device_id] => Array
(
[0] => dv1002
[1] => dv1002
)
[date_time] => Array
(
[0] => MongoDate Object
(
[sec] => 1477476049
[usec] => 0
)
[1] => MongoDate Object
(
[sec] => 1477476313
[usec] => 0
)
)
[dc_voltage] => Array
(
[0] => dv1
[1] => dvv2
)
[dc_current] => Array
(
[0] => dc1
[1] => dc2
)
[output_voltage] => Array
(
[0] => output voltage1
[1] => output voltage2
)
[output_current] => Array
(
[0] => output current1
[1] => output current2
)
)
)
[ok] => 1
)
我需要以下结果。
Array
(
[waitedMS] => 0
[result] => Array
(
[0] => Array
(
[device_id] => dv1002
[date_time] => MongoDate Object
(
[sec] => 1477476313
[usec] => 0
)
[dc_voltage] => dvv2
[dc_current] => dc2
[output_voltage] => output voltage2
[output_current] => output current2
)
)
[ok] => 1
)