JavaSpring数据mongodb如何使用通配符?
Java Spring data mongodb how to use wildcards?
我的 mongodb 中有一个名为 "name" 的字段。我在 spring 数据中使用注释来支持查询。我的问题是,有没有办法支持通配符?即,如果我有 "name" 的值称为 "Robert"、"Roberto" "Ramano",我可以支持允许我将 say "R" 传递给函数的查询,并且它将匹配以 R 开头的所有内容?现在我基本上必须做 Robert 的 "exact spelling" 或这些名字中的任何一个才能获得完全匹配。
我知道如何直接使用 mongodb 进行通配符搜索,但不确定如何在 java 中使用 spring 数据进行搜索。我有一个模型 class 代表我的学生文档,我使用注释来描述如何查询。
db.users.find({"name": /.*m.*/})
我不知道如何将其转换为 java,因为我想传递一个变量。例如:
伪代码:
String myvar = "R";
db.users.find({/.*<variable here>*/})
以下是我的 "MongoRepository" 实现:
public interface UserRepository extends MongoRepository<UserId, String> {
{
@Query("{'name' : {$regex : ?0}}")
public List<Users> findByName(String username);
}
当我传入全名"Robert"时,它就能找到"Robert"。但是,如果我输入 "R",它什么也找不到。
你用 query method 试过了吗?
public interface UserRepository extends MongoRepository<UserId, String> {
{
public List<Users> findByNameLike(String username);
}
您为什么不像您尝试的那样以下列方式使用正则表达式:
public interface UserRepository extends MongoRepository<UserId, String> {
{
@Query("{'name' : {$regex : ?0}}")
public List<Users> findByName(String regexp);
}
并在您的服务中形成一个类似这样的查询:
@Mock
UserRepository userRepository;
String queryInput = "^R.*$";
List<Users> users = userRepository.findByName(queryInput);
在第 4.2 节here中找到更详细的答案
我的 mongodb 中有一个名为 "name" 的字段。我在 spring 数据中使用注释来支持查询。我的问题是,有没有办法支持通配符?即,如果我有 "name" 的值称为 "Robert"、"Roberto" "Ramano",我可以支持允许我将 say "R" 传递给函数的查询,并且它将匹配以 R 开头的所有内容?现在我基本上必须做 Robert 的 "exact spelling" 或这些名字中的任何一个才能获得完全匹配。
我知道如何直接使用 mongodb 进行通配符搜索,但不确定如何在 java 中使用 spring 数据进行搜索。我有一个模型 class 代表我的学生文档,我使用注释来描述如何查询。
db.users.find({"name": /.*m.*/})
我不知道如何将其转换为 java,因为我想传递一个变量。例如:
伪代码:
String myvar = "R";
db.users.find({/.*<variable here>*/})
以下是我的 "MongoRepository" 实现:
public interface UserRepository extends MongoRepository<UserId, String> {
{
@Query("{'name' : {$regex : ?0}}")
public List<Users> findByName(String username);
}
当我传入全名"Robert"时,它就能找到"Robert"。但是,如果我输入 "R",它什么也找不到。
你用 query method 试过了吗?
public interface UserRepository extends MongoRepository<UserId, String> {
{
public List<Users> findByNameLike(String username);
}
您为什么不像您尝试的那样以下列方式使用正则表达式:
public interface UserRepository extends MongoRepository<UserId, String> {
{
@Query("{'name' : {$regex : ?0}}")
public List<Users> findByName(String regexp);
}
并在您的服务中形成一个类似这样的查询:
@Mock
UserRepository userRepository;
String queryInput = "^R.*$";
List<Users> users = userRepository.findByName(queryInput);
在第 4.2 节here中找到更详细的答案