MongoDB case insensitive text query with parentheses

I have a very nasty problem with case sensitive query on mongodb.

I am using MongoTemplate in a web application and I need to execute case insensitive queries in a collection.

with this code

Query q = new Query(); q.addCriteria(Criteria.where("myField") .regex(Pattern.compile(fieldValue, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE))); return mongoTemplate.findOne(q,MyClass.class); 

I create the following query

 { "myField" : { "$regex" : "field value" , "$options" : "iu"}} 

which works fine when I have plain text, for example:

caPITella CapitatA

but ... but ... when there are parentheses (), the request does not work. It does not work at all, even the request text is written as written in the document ... Example:

request 1:

 {"myField" : "Ceratonereis (Composetia) costae" } -> 1 result (ok) 

request 2:

 { "myField" : { "$regex" : "Ceratonereis (Composetia) costae" , "$options" : "iu" }} -> no results (not ok) 

request 3:

 { "scientificName" : { "$regex" : "ceratonereis (composetia) costae" , "$options" : "iu" }} -> no results (....) 

So ... Am I doing something wrong? I forgot some Pattern.SOME to include in Pattern.compile ()? Any solution?

thanks

------ UPDATE ------

User3561036's answer helped me understand how the query should be built.

So, I decided by changing the build of the request to

 q.addCriteria(Criteria.where("myField") .regex(Pattern.compile(Pattern.quote(myFieldValue), Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE))); 

Output request

 { "myField" : { "$regex" : "\\Qhaliclona (rhizoniera) sarai\\E" , "$options" : "iu"}} 

work.

+6
source share
2 answers

If you use the $regex operator with a string as input, then you must specify literals for reserved characters, such as () .

Usually this is the only \ , but since it already does this on the line twice \\ :

 { "myField" : { "$regex" : "Ceratonereis \\(Composetia\\) costae" , "$options" : "iu" }} 
+2
source

Use $ strcasecmp. The aggregation structure was introduced in MongoDB 2.2. You can use the string operator "$ strcasecmp" to make case-insensitive string comparisons. This is more recommended and easier than using a regular expression.

0
source

Source: https://habr.com/ru/post/989391/


All Articles