Reputation: 169
I've got objects with string field and i want to search all objects which fits (case insensitive) to my array with string list.
e.g.
public class Person {
private String name;
}
List<String> list = Arrays.asList("teSt1", "tEsT2");
i can create condition like:
Criteria.where("name").in(list);
but i have no idea how to make it case insensitive (connect it with regex)
Thanks for any help
Upvotes: 2
Views: 3152
Reputation: 582
You can pass a list of Pattern instead of the strings in the in() method to achieve this.
import java.util.regex.Pattern;
Criteria.where("name").in(list.stream().map(s->Pattern.compile(s,Pattern.CASE_INSENSITIVE)).collect(Collectors.toList());
In case you would like an exact match and not a like search, you can try something like this.
Criteria.where("name").in(list.stream().map(s->Pattern.compile("^"+s+"$",Pattern.CASE_INSENSITIVE)).collect(Collectors.toList()));
This adds the regex of starts with and ends with, which makes it an exact match with case insensitiveness.
Upvotes: 1
Reputation: 169
I think it's impossible to build it that way
db.getCollection('collection').find( { "field" : { "$in" : [{"$regex": '...', "$options": "i"}] } })
query like that returns error, i figured out solution which is very very not optimal, but works. Just build regex criteria for all list values and connect it with OR, like:
Criteria orCriteria = new Criteria();
Criteria[] regExList = new Criteria[list.size()];
IntStream.range(0, list.size()).forEach(i -> {
regExList[i] = Criteria.where("field").regex(list.get(i), "i");
});
orCriteria.orOperator(regExList);
Upvotes: 1