Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine MongoDB ODM search in two or more fields

I would like to write a query in Doctrine Mongo ODM that searches by regex in two or more fields. In SQL it would look like:

SELECT * FROM user WHERE name LIKE %search% OR surname LIKE %search%;

I can write a query for one field like this:

$qb->field('surname')->equals(new \MongoRegex('/.*'.$this->search.'.*/i'));

but I'm at a loss when i try to search in more fields.

Thanks for any help

like image 587
bazo Avatar asked Jan 09 '12 15:01

bazo


2 Answers

well actually it is quite simple, i found out 5 mins after posting this question

$qb->addOr($qb->expr()->field('surname')->equals(new \MongoRegex('/.*'.$this->search.'.*/i')));
$qb->addOr($qb->expr()->field('name')->equals(new \MongoRegex('/.*'.$this->search.'.*/i')));
like image 186
bazo Avatar answered Nov 13 '22 11:11

bazo


You need to use the $or operator. I'm not sure how this is done in doctrine but you are looking for the equivalent of this in the shell:

db.people.find({ $or: [{surname: /^regex1/}, {surname: /^regex2/}] })
like image 2
Tyler Brock Avatar answered Nov 13 '22 13:11

Tyler Brock