Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find with regular expression MongoDB + PHP

I'm trying to do a PHP find over a MongoDB collection using MongoRegex, but I'm not able to make it work. The code is quite easy:

$cursor = $this->collection->find($params)
//$params has this value:
//Array
//(
//    [name] => MongoRegex Object
//    (
//       [regex] => .*victor.*
//       [flags] => i
//    )
//    [login] => MongoRegex Object
//    (
//        [regex] => .*victor.*
//        [flags] => i
//    )
//)

This $params array is constructed with this function:

function toRegEx($entryVars=array()){
    $regexVars = array();
    foreach($entryVars as $var => $value){
        $regexVal = html_entity_decode($value);
        $regexVars[$var] = new MongoRegex("/.*".$regexVal.".*/i");
    }
    return $regexVars;
}

For some reason, this query is only returning the values which makes an exact match (i.e. the documents where login or name are exactly "victor"). What I want is that the query returns all the documents where login and/or name contains the word "victor". I'm pretty sure I'm missing something basic, but I'm not being able to find it. Any help is appreciated. Thanks!

like image 793
Vithozor Avatar asked Nov 30 '25 19:11

Vithozor


1 Answers

I suppose you simply anchored the regexp to the beginning of the subject string (^), try without :

$regexVars[$var] = new MongoRegex("/".$regexVal."/i");

EDIT: Also, if the print_r dump of the $params array above is accurate, you're probably missing a $or statement somewhere to reflect your conditions. By default, the mongodb query criteria are linked with a "and" logic, so your query will return records matching regexps on both fields only.

like image 108
Calimero Avatar answered Dec 02 '25 09:12

Calimero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!