Symfony2 + Need to use the regular expression in doctrine's mongodb ODM to check case insensitive check
Asked Answered
P

2

0

I want to do the case insensitive check for the query. previously I am using MongoRegex as describe in the this ticket

But as per the Php.net this is now deprecated, so can't use it, they suggest to use MongoDB\BSON\Regex but I am not sure how use this in symfony2. but it throws class not found exception if I try to use it.

Please let me know the possible solution. Or any other way to do the case insensitive check in the ODM custom query (may be in field function)

Thank you so much.

Pussy answered 21/4, 2016 at 6:46 Comment(4)
Did you try the regular /pattern/i? Or /(?i)pattern/?Scarborough
You can't use MongoRegex, then please provide the code that works for you and when describe when it stops working.Scarborough
how to use '/pattern/i' in findOneBy query of doctrine?, I am new to doctrine so not sure how to include this in findOneBy pareameterPussy
@WiktorStribiżew these are the docs for ORM, not ODMDixson
P
1

I have written custom query as follows :

$name = 'abc'
$db->createQuerBuilder()
   ->distinct('username')
   ->field('username')->where('function(){ var pattern = /^' . $name . '$/i; return pattern.test(this.username); }')
   ->getQuery()
   ->execute()
   ->getSingleResult();

I have used mongodbs where function with JavaScript test function. Reference link

Pussy answered 25/4, 2016 at 8:30 Comment(0)
D
0

If using MongoDB\BSON\Regex yields "Class Not found" exception then you're using legacy driver and need to use \MongoRegex. As you've seen the whole driver is deprecated but you can still use it, also it's still the only one ODM officially supports (new driver can be used if combined with polyfill such as mongo-php-adapter).

So to answer your question, case insensitive search will look like (given $qb is a query builder):

$qb->field('something')->equals(new \MongoRegex("/regex/i"));
Dixson answered 21/4, 2016 at 7:12 Comment(4)
but I cant use MongoRegex. is there other oprionsPussy
Why can't you use MongoRegex?Dixson
as per the php.net (php.net/manual/en/class.mongoregex.php) this class is deprecated. they have given another php.net/manual/en/class.mongodb-bson-regex.php but this is not working for mePussy
MongoDB\BSON\Regex is from new driver (i.e. mongodb), to use this you'd need to install it (and mentioned polyfill to use ODM at all). But since you're using legacy driver (i.e. mongo) you have to use its classes like MongoRegex to search by regular expression.Dixson

© 2022 - 2024 — McMap. All rights reserved.