MongoDB aggregate query using PHP driver

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

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 }
] )

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

The error from the above PHP code is:

{"errmsg":"exception: wrong type for field (pipeline) 3 != 4","code":13111,"ok":0}

Any ideas? Thanks.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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

Solution 2

You can also use the JSON array directly:

$json = [
  '{ $project : { day : { $dayOfYear : "$executed" } } },
   { $group : { _id : { day : "$day" }, n : { $sum : 1 } } } , 
   { $sort : { _id : -1 } } , 
   { $limit : 14 }'
];

$pipeline = [];
foreach ($json as $stage) {
   array_push($pipeline, toPHP(fromJSON($stage)));
}
$result = $c->aggregate($pipeline);

You can also use combination like this:

use function MongoDB\BSON\toRelaxedExtendedJSON;
use function MongoDB\BSON\fromPHP;
use function MongoDB\BSON\toPHP;
use function MongoDB\BSON\fromJSON;

$operator = '$dayOfYear';
$json = [];
array_push($json, toRelaxedExtendedJSON(fromPHP(
   array('$project ' => array('day' => array($operator => '$executed')))
)));
array_push($json, 
   '{ $group : { _id : { day : "$day" }, n : { $sum : 1 } } } , 
    { $sort : { _id : -1 } } , 
    { $limit : 14 }'
);
$pipeline = [];
foreach ($json as $stage) {
   array_push($pipeline, toPHP(fromJSON($stage)));
}
$result = $c->aggregate($pipeline);

or

$operator = '$dayOfYear';
$json = [];
array_push($json, 
   '{ $group : { _id : { day : "$day" }, n : { $sum : 1 } } } , 
    { $sort : { _id : -1 } } , 
    { $limit : 14 }'
);
$pipeline = [];
array_push($pipeline, array('$project ' => array('day' => array($operator => '$executed'))));
foreach ($json as $stage) {
   array_push($pipeline, toPHP(fromJSON($stage)));
}
$result = $c->aggregate($pipeline);

If your aggregation query is dynamic or based on user-input be aware of NoSQL-Injection!
https://www.acunetix.com/blog/web-security-zone/nosql-injections/

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply