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?

j0k
  • 22,600
  • 28
  • 79
  • 90
chaostheory
  • 1,621
  • 4
  • 20
  • 36
  • 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 http://php.net/manual/en/class.mongoregex.php http://stackoverflow.com/questions/36761669/symfony2-need-to-use-the-regular-expression-in-doctrines-mongodb-odm-to-check That is why I have given this answer for those who may have concern about this. – Anuja P Jul 13 '16 at 11:15

3 Answers3

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.

jmikola
  • 6,892
  • 1
  • 31
  • 61
  • 2
    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); http://php.net/manual/en/mongodb-bson-regex.construct.php – Anuja P Apr 20 '16 at 11:22
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

Community
  • 1
  • 1
Shahbaz
  • 3,433
  • 1
  • 26
  • 43
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.

Ali Khalili
  • 1,504
  • 3
  • 18
  • 19