Doctrine MongoDB ODM search in two or more fields
Asked Answered
H

2

11

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

Health answered 9/1, 2012 at 15:58 Comment(0)
H
17

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')));
Health answered 10/1, 2012 at 10:14 Comment(0)
Y
2

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/}] })
Yachtsman answered 9/1, 2012 at 18:36 Comment(1)
Also, be aware that indexes will only be used for rooted case sensitive regular expressions.Yachtsman

© 2022 - 2024 — McMap. All rights reserved.