使用聚合将_id分组的PHP中的MongoDB无法正常工作 [英] MongoDB in PHP using aggregate to group by _id is null not working

查看:91
本文介绍了使用聚合将_id分组的PHP中的MongoDB无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用此MongoDB命令和过滤器,当我将其转换为PHP时,它的工作量很大,希望有一个可以帮助我解释其为什么不起作用的东西吗?

I'm trying to use this MongoDB command and filter, its dosen work when i translate it to PHP, hope there are one there can help me to explain why its not working?

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
)

我希望对这个问题有简单的解释,谢谢大家的帮助.

i hope there are simple explaining on this issue thanks for helping guys.

推荐答案

使用 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 ]
        ]
    ]
]

这篇关于使用聚合将_id分组的PHP中的MongoDB无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆