1

我知道有很多关于“MongoDB $ 或 PHP”的主题,但我无法理解这一点;

假设我有一个集合Compagnies

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

我需要使用正则表达式对此集合执行“或”查询。所以我做了:

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行吗?现在如果我这样做:

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

结果将只是第一行。我不明白为什么第二行与查询不匹配,因为名称中还有“B”。'$or' 运算符的行为似乎类似于 '$and'。

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

谢谢 :)

4

1 回答 1

1

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

$Mongo->Compagnies->find(
array(
    '$or'   =>  array(
        array(
            "Name"             =>  $regex,
        ),
         array(
            "Service"          =>  $regex,
        ),
         array(
            "Description"      =>  $regex,
        ),
        )
    )
);
于 2016-11-16T10:54:16.277 回答