Mongodb Aggregate Query Using PHP Driver

MongoDB aggregate query using PHP driver

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
)
));

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 aggregation with match and sort order

I've found a solution. I have changed this line:

$manager = new MongoDB\Driver\Manager("mongodb://admin:$psw@localhost:27017");

into this:

$manager = new MongoDB\Driver\Manager("mongodb://admin:$psw@localhost:27017/db_name");

That was an authentication problem.

php mongoDB aggregate() returning MongoDB\Driver\Cursor Object instead of result

The aggregate method returns a Cursor, see the documentation for more information.

If you need to use the result as an array you can use iterator_to_array, like this:

$resultAsArray = iterator_to_array( $h->aggregate($aggregateArr), false );

Now, $resultAsArray is an array.



Related Topics



Leave a reply



Submit