MongoDB Aggregation PHP, Group by Hours

前端 未结 1 417
滥情空心
滥情空心 2021-01-01 07:56

I have documents with the following format

{
  \"_id\" : ObjectId(\"12e123123123123123\"),
  \"client_id\" : \"12345667889\",
  \"resource\" : \"test/test\",         


        
相关标签:
1条回答
  • 2021-01-01 08:36

    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
    }
    
    0 讨论(0)
提交回复
热议问题