MongoDB聚合PHP,按小时分组

时间:2013-01-02 10:08:01

标签: php mongodb mongodb-php

我的文件格式如下

{
  "_id" : ObjectId("12e123123123123123"),
  "client_id" : "12345667889",
  "resource" : "test/test",
  "version" : "v2",
  "ts" : new Date("Wed, 02 Jan 2013 15:34:58 GMT +08:00")
}

ts是MongoDate()字段。

我试图在php中使用MongoDB聚合函数按client_id分组,小时和计数用法显示在表格/图表中

这是我目前的尝试

$usage = $this->db->Usage->aggregate(array(array(
  '$project' => array(
    'hour' => array(
      'years' => array( '$year' => '$ts' ),
      'months' => array( '$month' => '$ts' ),
      'days' => array( '$dayOfMonth' => '$ts' ),
      'hours' => array( '$hour' => '$ts' ),
    )
  ),
  '$group' => array(
    '_id' => array(
      'client_id' => '$client_id',
      'hour' => '$hour',
    ),
   'number' => array('$sum' => 1),
  )
)));

不幸的是,我回复的回答只是通过client_id进行分组,而不是别的。

[result] => Array
    (
        [0] => Array
            (
                [_id] => Array
                    (
                        [client_id] => adacf8deba7066e4
                    )

                [number] => 12
            )

    )

任何人都能指出我正确的方向,或者有一个小时的另一个解决方案吗?

- Fixed-- PHP要求您将每个管道放在一个单独的数组中,并将整个数据放入一个数组中。在JohnnyHK的帮助下查看下面的更新解决方案

$usage = $this->db->Usage->aggregate(array(array(
        '$project' => array(
            'client_id' => 1,
            'hour' => array(
                'years' => array( '$year' => '$ts' ),
                'months' => array( '$month' => '$ts' ),
                'days' => array( '$dayOfMonth' => '$ts' ),
                'hours' => array( '$hour' => '$ts' ),
            )
        )),array(
        '$group' => array(
            '_id' => array(
                'client_id' => '$client_id',
                'hour' => '$hour',
            ),
            'number' => array('$sum' => 1),
        )
    )));

1 个答案:

答案 0 :(得分:4)

它不应该创建您看到的结果,但您需要在client_id运算符中包含$project,以便$group运算符可以使用它。

'$project' => array(
  'client_id' => 1,
  'hour' => array(
    'years' => array( '$year' => '$ts' ),
    'months' => array( '$month' => '$ts' ),
    'days' => array( '$dayOfMonth' => '$ts' ),
    'hours' => array( '$hour' => '$ts' ),
  )
),

在我做出改变后,shell等效工作了:

 
db.test.aggregate(
    { $project: {
        hour: {
            years: {$year: '$ts'},
            months: {$month: '$ts'},
            days: {$dayOfMonth: '$ts'},
            hours: {$hour: '$ts'}
        },
        client_id: '$client_id'
    }},
    { $group: {
        _id: { client_id: '$client_id', hour: '$hour' },
        number: { $sum: 1}
    }})

返回:

 
{
  "result": [
    {
      "_id": {
        "client_id": "12345667889",
        "hour": {
          "years": 2013,
          "months": 1,
          "days": 2,
          "hours": 7
        }
      },
      "number": 1
    }
  ],
  "ok": 1
}