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.