I have documents with the following format
{
\"_id\" : ObjectId(\"12e123123123123123\"),
\"client_id\" : \"12345667889\",
\"resource\" : \"test/test\",
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
}