MongoDB正则表达式查询在Java / Spring中不起作用

时间:2019-04-08 10:19:47

标签: java regex spring mongodb

我正在尝试在数据库中查找配方,其标题包含method参数中的字符串。我不希望它必须是完全匹配的(现在是这样),但是如果字符串在配方的“标题”字段中的任何位置存在,则应将其视为匹配项。这意味着,如果我要搜索“牛肉”,那么您会期望得到很多食谱。这是我的代码:

import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;

public interface RecipeRepository extends MongoRepository<Recipe, String> {

    public Recipe findByTitle(String title);

    //@Query("{ 'title': /.*?0.*/ }")
    @Query("{ 'title' : ?0 }")
    public List<Recipe> findByTitleLike(String title);

} 

该代码当前可与?0占位符一起使用,并找到与标题完全匹配的匹配项。您可以在上面的注释行中看到一个正则表达式,其中我试图匹配title参数两侧的任何内容,因此,基本上如果标题中存在它,则应该匹配。

我按照以下答案构建了正则表达式查询:https://stackoverflow.com/a/3305687/8887398

我还查看了以下文档:https://docs.mongodb.com/manual/reference/operator/query/regex/

运行代码时,我不断收到此错误:

Unsatisfied dependency expressed through field 'repository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'recipeRepository': Invocation of init method failed; nested exception is com.mongodb.util.JSONParseException: 
{ 'title': /.*"_param_0".*/ }

有一个小箭头指向字符串中的特定位置,不确定是否相关:

enter image description here

我真的不确定我在做什么错。谁能看到我的错误?错误消息也没有真正帮助我。

1 个答案:

答案 0 :(得分:0)

您很可能已经找到了解决方案,但对于那些仍在寻找的人:

@Query('title':'.\*?0.\*')