本文介绍了MongoDB对带括号的文本不区分大小写的查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对mongodb的不区分大小写的查询有一个非常烦人的问题.

I have a very annoying problem with a case insensitive query on mongodb.

我在Web应用程序中使用MongoTemplate,并且需要在集合上执行不区分大小写的查询.

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

使用此代码

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);

我创建以下查询

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

当我有简单的文本时,可以完美地工作,例如:

that works perfectly when I have simple text, for example:

caPITella CapitatA

但是...但是...当有括号()时,查询不起作用.根本不起作用,甚至查询文本的写法也与文档中的写法一样.示例:

but...but...when there are parenthesis () the query doesn't work.It doesn't work at all, even the query text is wrote as is wrote in the document...Example:

查询1:

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

查询2:

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

查询3:

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

所以...我做错了什么?我忘记了一些Pattern.Some包含在Pattern.compile()中吗?有解决办法吗?

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

谢谢

------更新------

user3561036的回答帮助我弄清楚了必须如何构建查询.

The answer of user3561036 helped me to figure how the query must be built.

因此,我已通过修改以下查询的构建来解决

So, I have resolved by modifying the query building in

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

输出查询

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

有效.

推荐答案

如果使用 $regex 运算符,其输入为字符串",然后必须引用保留字符(如())的文字.

If using the $regex operator with a "string" as input then you must quote literals for reserved characters such as ().

通常这是一个\,但是由于它已经在一个字符串中,因此您要进行两次\\:

Normally that's a single \, but since it's in a string already you do it twice \\:

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

这篇关于MongoDB对带括号的文本不区分大小写的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 22:01