Daniel
Daniel

Reputation: 6491

Spring MongoTemplate - find by regex in collection

Saying i have a multivalue field in a mongo document:

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

What would be the correct criteria for querying a regex in that field?

I've tried

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

But that results in

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

Upvotes: 3

Views: 7923

Answers (2)

user3863488
user3863488

Reputation: 227

This is working

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

Upvotes: 0

Daniel
Daniel

Reputation: 6491

So after many trial and errors, turns out it's simpler (although a little counter-intuitive in my opinion) than it thought:

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

Upvotes: 3

Related Questions