【问题标题】:Spring MongoTemplate - find by regex in collectionSpring MongoTemplate - 通过集合中的正则表达式查找
【发布时间】:2016-02-25 09:47:57
【问题描述】:

说我在 mongo 文档中有一个多值字段:

public class MongoEntity{
    private List<String> field;
}

在该字段中查询正则表达式的正确 criteria 是什么?

我试过了

Criteria.where(searchText).regex(searchText).in("field");

但这会导致

org.springframework.data.mongodb.UncategorizedMongoDbException: 
Can't canonicalize query: BadValue unknown top level operator: $in; 
nested exception is com.mongodb.MongoException: Can't canonicalize query: BadValue unknown top level operator: $in

【问题讨论】:

  • 你是怎么解决这个问题的?这将非常有帮助,非常感谢。

标签: java regex spring mongodb mongotemplate


【解决方案1】:

因此,经过多次尝试和错误,结果证明它比想象的要简单(尽管在我看来有点违反直觉):

Criteria.where("field").regex(searchText);

【讨论】:

  • 这对我不起作用。我有 List 标签,想用 searchStr 搜索我有这样的代码 String regex = ".*" + searchText + ".*"; Criteria.where("tags").regex(regex)。但这并没有给出结果。
【解决方案2】:

这是有效的

List<Pattern> regs = new ArrayList<Pattern>()
regs.add(Pattern.compile(regex, Pattern.CASE_INSENSITIVE))
Criteria.where("tags").regex(regs)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-10
    • 1970-01-01
    • 2015-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    • 1970-01-01
    相关资源
    最近更新 更多