MongoDB
 SQL >> Database >  >> NoSQL >> MongoDB

Raggruppare per ore in un’aggregazione MongoDB PHP

Se una fase $group usa un campo, quel campo deve essere incluso prima nella fase $project. Per esempio, client_id va mantenuto nel documento intermedio.

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

Così il raggruppamento può accedere correttamente a client_id.