使用PHP驱动程序的MongoDB聚合查询 [英] MongoDB aggregate query using PHP driver
问题描述
我有一个有效的MongoDB
聚合查询,可以通过MongoDB shell运行它.但是,我正在尝试将其转换为可与官方PHP
Mongo驱动程序(http://php.net/manual/en/mongocollection.aggregate.php)一起使用.
I have a working MongoDB
aggregate query which I can run via the MongoDB shell. However, I am trying to convert it to work with the official PHP
Mongo driver (http://php.net/manual/en/mongocollection.aggregate.php).
这是工作中的原始MongoDB查询:
Here is the working raw MongoDB query:
db.executions.aggregate( [
{ $project : { day : { $dayOfYear : "$executed" } } },
{ $group : { _id : { day : "$day" }, n : { $sum : 1 } } } ,
{ $sort : { _id : -1 } } ,
{ $limit : 14 }
] )
这是我使用Mongo驱动程序在PHP
中的尝试(不起作用):
Here is my attempt (not working) in PHP
using the Mongo driver:
$result = $c->aggregate(array(
'$project' => array(
'day' => array('$dayOfYear' => '$executed')
),
'$group' => array(
'_id' => array('day' => '$day'),
'n' => array('$sum' => 1)
),
'$sort' => array(
'_id' => 1
),
'$limit' => 14
));
上面的PHP代码中的错误是:
The error from the above PHP code is:
{"errmsg":"exception: wrong type for field (pipeline) 3 != 4","code":13111,"ok":0}
有什么想法吗?谢谢.
推荐答案
Javascript中的参数是由4个对象组成的数组,每个对象具有一个元素,而在PHP中,则是具有4个元素的关联数组(对象).这将代表您的Javascript:
The parameter in your Javascript is an array of 4 objects with one element each, in your PHP it's an associative array (object) with 4 elements. This would represent your Javascript:
$result = $c->aggregate(array(
array(
'$project' => array(
'day' => array('$dayOfYear' => '$executed')
),
),
array(
'$group' => array(
'_id' => array('day' => '$day'),
'n' => array('$sum' => 1)
),
),
array(
'$sort' => array(
'_id' => 1
),
),
array(
'$limit' => 14
)
));
此外,如果您至少有PHP5.4,则可以使用更简单的数组语法.那么,向PHP的转换就变得微不足道了,您只需将花括号替换为方括号并将冒号替换为箭头即可:
In addition, if you have at least PHP5.4, you can use simpler array syntax. Transformation to PHP is then trivial, you simply replace curly braces with square brackets and colons with arrows:
$result = $c->aggregate([
[ '$project' => [ 'day' => ['$dayOfYear' => '$executed'] ] ],
[ '$group' => ['_id' => ['day' => '$day'], 'n' => ['$sum' => 1] ] ],
[ '$sort' => ['_id' => 1] ],
[ '$limit' => 14 ]
]);
这篇关于使用PHP驱动程序的MongoDB聚合查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!