使用聚合按_id分组的PHP中的MongoDB为null无效

时间:2016-01-08 10:41:32

标签: php mongodb

我正在尝试使用这个MongoDB命令和过滤器,当我将它翻译成PHP时它的工作,希望有一个可以帮助我解释为什么它不起作用?

MongoDB语法:

db.getCollection('product').aggregate(
   [
      { $match: { 'Store.Title': { $regex: 'apc', $options: 'gi' } } },
      { $group: { _id: null, count: { $sum: 1 } } }
   ]
);

MongoDB的输出:

{
    "result" : [ 
        {
            "_id" : null,
            "count" : 774.0000000000000000
        }
    ],
    "ok" : 1.0000000000000000
}

PHP过滤器阵列:

[
    [
        '$match' => [
            'Store.Title' => ['$regex' => 'apc', '$options' => 'gi']
        ]
    ],[
        '$group' => [
            '_id' => 'null',
            'count' => [ '$sum' => 1 ]
        ]
    ]
]

PHP的输出:

Array
(
    [result] => Array
        (
        )

    [ok] => 1
)

我希望有一个关于这个问题的简单解释感谢帮助人们。

1 个答案:

答案 0 :(得分:1)

使用 MongoRegex 对象:

$search = "apc";
$where = array('Store.Title' => array('$regex' => new MongoRegex("/^$search/gi")));
// $where = array('Store.Title' => array('$regex' => new MongoRegex("/".$search."/gi")));

[
    [ '$match' => $where ],
    [
        '$group' => [
            '_id' => 'null',
            'count' => [ '$sum' => 1 ]
        ]
    ]
]