1

我有以下格式的文件

{
  "_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
            )

    )

谁能指出我正确的方向,或者有另一种按小时分组的解决方案?

--已修复-- 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),
        )
    )));
4

1 回答 1

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
}
于 2013-01-02T14:09:22.233 回答