使用PHP驱动程序进行MongoDB组查询

时间:2013-01-30 22:37:34

标签: php mongodb group-by

我正在尝试使用官方PHP驱动程序和组(http://www.php.net/manual/en/mongocollection.group.php)函数将工作MongoDB组查询转换为PHP等效项。

以下是正常工作原始MongoDB查询:

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

这是我的无效 PHP代码:

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

print_r()的{​​{1}}:

$result

谢谢!

1 个答案:

答案 0 :(得分:1)

condition正在比较字符串而不是日期。您需要MongoDate代替。类似的东西:

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