问题
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),
)
)));
回答1:
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
}
来源:https://stackoverflow.com/questions/14120123/mongodb-aggregation-php-group-by-hours