MongoDB Aggregation PHP, Group by Hours

安稳与你 提交于 2019-11-30 10:36:25

It shouldn't create the results you're seeing, but you do need to include client_id in your $project operator so that it's available to the $group operator.

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

The shell equivalent worked after I made that change:

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}
    }})

returned:

{
  "result": [
    {
      "_id": {
        "client_id": "12345667889",
        "hour": {
          "years": 2013,
          "months": 1,
          "days": 2,
          "hours": 7
        }
      },
      "number": 1
    }
  ],
  "ok": 1
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!