db.tickers.aggregate(
{ $project:
{_id: 0,
year: {$year: '$date'},
month: {$month: '$date'},
day: {$dayOfMonth: '$date'},
hour: {$hour: '$date'},
avg: '$ticker.avg'
}
},
{ $group: {
_id: { year: '$year', month: '$month', day: '$day', hour: '$hour' },
avg: { $avg: '$avg' }
}
},
{ $sort: {
'year':1, month:1, day:1, hour:1
}
}
);
如何在Lithium中编写上述查询?
我试过了:
$mongodb = Connections::get('default')->connection;
$tick = Tickers::connection()->connection->command(array(
'aggregate' => 'tickers',
'pipeline' => array(
'_id'=>null,
array('year' => array('$year' => '$date')),
array('month' => array('$month' => '$date')),
array('day' => array('$dayOfMonth' => '$date')),
array('hour' => array('$hour' => '$date')),
array('avg' => '$ticker.avg'),
),
array( '$group' => array( '_id' => array(
'year'=>'$year',
'month'=>'$month',
'day'=>'$day',
'hour'=>'$hour'
),
'avg' => array('$avg' => '$ticker.avg'),
),
array('$sort'=>array(
'year'=>1,
'month'=>1,
'day'=>1,
'hour'=>1
))
)
));
这是对问题的回复,我有mongodb: find summary of records
问题查找 - 答案摘要的答案是正确的,但我不能把它放在锂电池中。
提前致谢:)
答案 0 :(得分:2)
您忘记了对象的$project
级别。试试这个:
$tick = Tickers::connection()->connection->command(array(
'aggregate' => 'tickers',
'pipeline' => array(
array( '$project' => array(
'_id' => 0,
'year' => array('$year' => '$date'),
'month' => array('$month' => '$date'),
'day' => array('$dayOfMonth' => '$date'),
'hour' => array('$hour' => '$date'),
'avg' => '$ticker.avg',
)),
array( '$group' => array( '_id' => array(
'year'=>'$year',
'month'=>'$month',
'day'=>'$day',
'hour'=>'$hour'
),
'avg' => array('$avg' => '$ticker.avg'),
)),
array('$sort'=>array(
'year'=>1,
'month'=>1,
'day'=>1,
'hour'=>1
))
)
));