I have documents with the following format
{
"_id" : ObjectId("12e123123123123123"),
"client_id" : "12345667889",
"resource" : "test/test",
"version" : "v2",
"ts" : new Date("Wed, 02 Jan 2013 15:34:58 GMT +08:00")
}
The ts
is a MongoDate() field.
I am trying to use MongoDB aggregate function in php to group by client_id and hour and count usage to display in a table/graph
This is my current attempt
$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),
)
)));
Unfortunately my response I am getting back is just grouping by the client_id and nothing else.
[result] => Array
(
[0] => Array
(
[_id] => Array
(
[client_id] => adacf8deba7066e4
)
[number] => 12
)
)
Anyone able to point me in the right direction, or have another solution to group by hour?
--Fixed-- PHP requires that you put each pipeline in a separate array as well as putting the whole thing in an array. see update solution below with help from 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),
)
)));