2

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

Gwiazdek
  • 149
  • 1
  • 8
  • If you are extending `CrudRepository` you can try to create a method called `findByNameInIgnoreCase(List names)` – Joqus Aug 10 '18 at 18:41
  • thanks for reply, i found that but it's not solution, it's only part of method, there is also criteria for keyword etc – Gwiazdek Aug 10 '18 at 21:58
  • Have a look at this useful answers about `criteria` https://stackoverflow.com/a/44278901/8112217 and https://stackoverflow.com/a/44278967/8112217 – tsarenkotxt Aug 11 '18 at 04:11

2 Answers2

1

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.

0

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);
Gwiazdek
  • 149
  • 1
  • 8