1

我有一个名为“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")
 }  

每分钟都会从报价和交易中插入数据。

我想从上述数据中找到每小时的平均值。

我试过:

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 条记录...

4

1 回答 1

3

日期运算符必须在$project操作中使用,而不是 a $group,因此您需要这样做(在 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
}
于 2013-01-02T13:18:58.173 回答