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
Wordpress, Nginx Proxy and Subdirectory: Wp-Login.PHP Redirects to Domain
Are PHP Keywords Case-Sensitive
How to Set PHP's Auto_Prepend_File Directive Per Directory
Php: What Is the Purpose of Session_Name
Pcntl Runs the Same Code Several Times, Assistance Required
How Check Memory Location of Variable in PHP
Merge a Table and a Change Log into a View in Postgresql
PHP Undefined Variable in a Closure
Regular Expression to Remove CSS Comments
Laravel 5 Multiple Download File
PHP Foreach() with Arrays Within Arrays
PHP Curl with Curlopt_Followlocation Error
How to Allow a User to Download a File Which Is Stored Outside of the Webroot
Adding User Custom Field Value to Order Items Details
How to Backup/Export the Connected Database Database.SQL File in Laravel