0

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!

1 Answer 1

1

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));
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. Anyway I can reverse the sort though, instead of returning 1/30/2013 to 1/1/2013, I want 1/1/2013 to 1/30/2013. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.