mongodb:查找记录摘要 [英] mongodb: find summary of records
本文介绍了mongodb:查找记录摘要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个名为"tickers"的收藏夹
I have a collection called 'tickers'
数据的格式为:
{
"_id": ObjectId("50d192b5480cf44157000000"),
"ticker": {
"high": 13.38839,
"low": 13.1225,
"avg": 13.244705635,
"vwap": 13.258414151,
"vol": NumberInt(21562),
"last_all": 13.57334,
"last_local": 13.3324,
"last": 13.3324,
"buy": 13.33185,
"sell": 13.3749
},
"date": ISODate("2012-12-19T10: 11: 01.439Z")
}
每隔分钟从报价和交易中插入数据.
Data is inserted every minute from the price quotes and transactions.
我想从上述数据中查找每个小时的平均值.
I want to find the average for every hour from the above data.
我尝试过:
command(array(
'aggregate' => 'tickers',
'pipeline' => array(
array(
'$group' => array(
'_id' => array(
'year'=>'$year($date)',
'month'=>'$month($date)',
'day'=>'$dayOfMonth($date)',
'hour'=>'$hour($date)'
),
'avg' => array( '$avg' => '$ticker.avg') ,
),
)))
但只能获得一份记录:
Array (
[result] => Array (
[0] => Array (
[_id] => Array ( )
[avg] => 13.407843889084 ) )
[ok] => 1
)
正在等待100天的至少100条记录...
Expecting at least 100 records for 100 days...
推荐答案
日期运算符必须在$project
操作中使用,而不是在$group
中使用,因此您需要这样做(在shell中) :
The date operators must be used in a $project
operation, not a $group
, so you need to do it like this instead (in the shell):
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'}
}});
给出以下结果:
{
"result": [
{
"_id": {
"year": 2012,
"month": 12,
"day": 19,
"hour": 10
},
"avg": 13.244705635
}
],
"ok": 1
}
这篇关于mongodb:查找记录摘要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文