Aerkaos Aerkaos - 24 days ago 7
PHP Question

MongoDB '$or' and regex in PHP

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

Assuming I've a collection

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


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


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'.

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?

Thank you :)

Answer

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