MongoDB '$or' 和 PHP 中的正则表达式 [英] MongoDB '$or' and regex in PHP

查看:45
本文介绍了MongoDB '$or' 和 PHP 中的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有很多关于MongoDB $ or PHP"的主题,但我无法理解;

I know there are tons of subjects about "MongoDB $or PHP", but I'm unable to understand this;

假设我有一个集合 Compagnies:

$Mongo->Compagnies->insert({"Name":"BoldLine", "Service":"Billing", "Description":"Hello World"});
$Mongo->Compagnies->insert({"Name":"Behobe", "Service":"Development", "Description":"Here we are cool"});

我需要使用正则表达式对该集合执行或"查询.所以我做到了:

My need is to execute an 'or' query on this collection, using regex. So I did:

use \MongoRegex as MR;

$regex = new MR ("/B/i");    //Where field contains the letter 'B'

$Mongo->Compagnies->find(
    array(
        '$or'   =>  array(
            array(
                "Name"          =>  $regex,
                "Service"       =>  $regex,
                "Description"   =>  $regex
                )
            )
        )
);

但是结果是0.为什么?结果不应该是2行?现在,如果我这样做:

But there is 0 result. Why? The result shouldn't be the 2 lines? Now if I do :

$Mongo->Compagnies->find(
    array(
        '$or'   =>  array(
            array(
                "Name"          =>  $regex,
                "Service"       =>  $regex
                )
            )
        )
);

结果只会是第一行.我不明白为什么第二行与查询不匹配,因为名称中还有B".似乎$or"运算符的作用类似于$and".

The result will be only the first line. I don't understand why the second line doesn't match the query, because there is also 'B' in the Name. It seems the '$or' operator acts like '$and'.

我错过了什么吗?即使一个或多个其他字段不包含此字母,我如何选择在 3 个字段之一中包含字母B"的所有实体?

Did I miss something? How can I select all entities containing the letter 'B' in one of the 3 fields, even if one or more other field doesn't not contain this letter?

谢谢:)

推荐答案

每个或条件应该在不同的数组中.试试这个:

Each or condition should be in different array. Try this:

$Mongo->Compagnies->find(
array(
    '$or'   =>  array(
        array(
            "Name"             =>  $regex,
        ),
         array(
            "Service"          =>  $regex,
        ),
         array(
            "Description"      =>  $regex,
        ),
        )
    )
);

这篇关于MongoDB '$or' 和 PHP 中的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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