Justin
Justin

Reputation: 45320

MongoDB group query using PHP driver

I am trying to convert a working MongoDB group query into the PHP equivalent using the official PHP driver and the group (http://www.php.net/manual/en/mongocollection.group.php) function.

Here is the working raw MongoDB query:

db.collection.group(
{
    keyf: function(doc) {
        var date = new Date(doc.executed);
        var dateKey = (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear();
        return {'day': dateKey};
     },
    cond: { executed: { $gt: new Date('01/01/2013') }},
    initial: { executions:0 },
    reduce: function(obj, prev) { prev.executions++; }
});

Here is my not working PHP code:

$keyf = new MongoCode('function(doc) {
    var date = new Date(doc.executed);
    var dateKey = (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear();
    return {\'day\': dateKey};
}');

$initial = array("executions" => 0);
$reduce = "function(obj, prev) { prev.executions++; }";
$conditionals = array("executed" => array('$gt' => "new Date('01/01/2013')"));

$result = $c->group($keyf, $initial, $reduce, array("condition" => $conditionals));

And the print_r() of $result:

Array
(
    [retval] => Array
        (
        )

    [count] => 0
    [keys] => 0
    [ok] => 1
)

Thanks!

Upvotes: 0

Views: 1252

Answers (1)

mjhm
mjhm

Reputation: 16695

You're condition is comparing a against a string not a date. You need a MongoDate instead. Something like:

$cond_date = new MongoDate(strtotime("2013-01-01 00:00:00"));
$conditionals = array("executed" => array('$gt' => $cond_date));

Upvotes: 1

Related Questions