Java spring-data mongo 中完全不区分大小写的匹配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23423464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 22:55:45  来源:igfitidea点击:

Exact case insensitive match in spring-data mongo

javaspringmongodbspring-dataspring-data-mongodb

提问by Jesse van Bekkum

I am using spring data with mongo, and a repository. Eg:

我正在使用带有 mongo 的 spring 数据和一个存储库。例如:

@Query("{ 'userName' : ?0 }")
public User findByUsername(String username);

I want to make this case insensitive. I have used the following queries:

我想让这个不区分大小写。我使用了以下查询:

"{'userName' : { $regex : ?0, $options: 'i' } }"

This works, but it not only matches testUser, but also estUser.

这有效,但它不仅匹配 testUser,还匹配 estUser。

I also tried

我也试过

"{'userName' : { $regex : ^?0$, $options: 'i' } }"

But this cannot parse the query, because it tries to insert quotes in the regex.

但这无法解析查询,因为它试图在正则表达式中插入引号。

com.mongodb.util.JSONParseException: 
({ $regex : ^"testUser"$, $options: 'i' }
            ^

I get the same kind of problems if I try to use a /.../i regex.

如果我尝试使用 /.../i 正则表达式,我会遇到同样的问题。

Is there any solution for this, without having to use mongoTemplate, or constructing the regex myself?

是否有任何解决方案,而不必使用 mongoTemplate 或自己构建正则表达式?

回答by Oliver Drotbohm

The easiest way probably is this:

最简单的方法可能是这样的:

interface UserRepository extends Repository<User, BigInteger> {

   List<User> findByUsernameIgnoreCase(String username);
}

回答by Sergey Benner

I just tried the following and it worked for me.

我只是尝试了以下方法,它对我有用。

 @Query(value = "{'name': {$regex : '^?0$', $options: 'i'}}")
    List<Item> findItemsByNameRegexExactMatch(String name);

回答by Vish Bansal

use Text Search in mongo db ,please use version 2.6+

在 mongo db 中使用文本搜索,请使用 2.6+ 版本

回答by Sudhakar Reddy

^ for the start, $ for the end

^ 开始,$ 结束

Aggregation aggregation = newAggregation( match(Criteria.where("fieldName").regex("^"+searchText+"$","i")) );