1

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

2
  • See php.net/manual/en/class.mongoregex.php#116000, this does not look like a regex issue, but how you use it with $or. Commented Nov 16, 2016 at 10:54
  • @Wiktor Stribiżew: Same result :( Edit: Yes, I guess it's a missuse of the or operator, I'm able to use the regex without any issues with no or-operator Commented Nov 16, 2016 at 10:55

1 Answer 1

1

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,
        ),
        )
    )
);
Sign up to request clarification or add additional context in comments.

2 Comments

Rectification, you are absolutely right, that was my syntax. Thank you!
This was the solution :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.