How can I use regular expressions with Doctrine's Mongodb ODM? How can I use regular expressions with Doctrine's Mongodb ODM? mongodb mongodb

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


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.


you can follow the Question on stack overflow for detailHow 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