How can I use regular expressions with Doctrine's Mongodb ODM?
Asked Answered
C

3

12

I'm trying to use regular expressions to query Mongodb using Doctrine's Mongodb ODM on Symfony 2.

I know the PHP mongo driver can do it. However, I don't know how to do this with Doctrine.

Do I use the same class? How do I reference MongoRegex from within Symfony?

Carlitacarlo answered 4/6, 2012 at 6:52 Comment(1)
For someone who don't wont to use the MongoRegex as that was deprecated can try this solution MongoRegex has been depecated as per the php.net/manual/en/class.mongoregex.php #36762169 That is why I have given this answer for those who may have concern about this.Hyperthermia
L
30

This came up a while ago on the doctrine-user mailing list. You can use the \MongoRegex class directly in your ODM queries:

$documentRepository->findBy(array(
    'foo' => new \MongoRegex('/^bar/'),
));

Or if using a query builder:

$queryBuilder->field('foo')->equals(new \MongoRegex('/^bar/'));

Keep in mind that front-anchored, case-sensitive regex patterns will be able to use indexes most efficiently. This is discussed in more detail in the Mongo docs.

Lifework answered 4/6, 2012 at 15:17 Comment(1)
I need to use new MongoDB\BSON\Regex class as MongoRegex is deperecated now. How can I use this in Symfony2 project. var_dump($regex); php.net/manual/en/mongodb-bson-regex.construct.phpHyperthermia
G
1

you can follow the Question on stack overflow for detail How to use Reserved characters in createQueryBuilder and MongoRegix,

Additionally, while /^a/, /^a./, and /^a.$/ match equivalent strings, they have different performance characteristics. All of these expressions use an index if an appropriate index exists; however, /^a./, and /^a.$/ are slower. /^a/ can stop scanning after matching the prefix. Mongo Docs Regix

Goethe answered 26/9, 2013 at 11:9 Comment(0)
H
1

The selected answer by jmikola is completely correct but as the \MongoRegex class is deprecated in newer versions of Doctrine, the new approach would be to use \MongoDB\BSON\Regex class. For example, in query builder approach, you may use:

$queryBuilder->field('foo')->equals(new \MongoDB\BSON\Regex('^bar'));

Note that unlike MongoRegex class, here the pattern should not be wrapped with delimiter characters.

Helldiver answered 26/5, 2022 at 16:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.