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

岁酱吖の 提交于 2019-12-03 16:42:16

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/10877369/how-can-i-use-regular-expressions-with-doctrines-mongodb-odm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!