作者:自行脑补 | 来源:互联网 | 2023-10-11 18:50
我有以下格式的文件
{
"_id" : ObjectId("12e123123123123123"),
"client_id" : "12345667889",
"resource" : "test/test",
"version" : "v2",
"ts" : new Date("Wed, 02 Jan 2013 15:34:58 GMT +08:00")
}
ts是MongoDate()字段.
我试图在php中使用MongoDB聚合函数按client_id分组,小时和计数用法显示在表/图中
这是我目前的尝试
$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),
)
)));
不幸的是,我回复的回答只是通过client_id进行分组,而不是别的.
[result] => Array
(
[0] => Array
([_id] => Array ( [client_id] => adacf8deba7066e4 )[number] => 12
)
)
任何人都能指出我正确的方向,或有一个小时的另一个解决方案?
– 固定 –
PHP要求您将每个管道放在一个单独的数组中,并将整个数据放入一个数组中.在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),
)
)));
解决方法:
它不应该创建您看到的结果,但是您需要在$project运算符中包含client_id,以便$group运算符可以使用它.
'$project' => array(
'client_id' => 1,
'hour' => array(
'years' => array( '$year' => '$ts' ),
'months' => array( '$month' => '$ts' ),
'days' => array( '$dayOfMonth' => '$ts' ),
'hours' => array( '$hour' => '$ts' ),
)
),
在我做出改变后,shell等效工作:
 
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}
}})
回来:
 
{
"result": [
{
"_id": {
"client_id": "12345667889",
"hour": {
"years": 2013,
"months": 1,
"days": 2,
"hours": 7
}
},
"number": 1
}
],
"ok": 1
}