how to query case insensitivity and contains with Spring MongoTemplate

Viewed 1722

I have JSON documents in MongoDB like these

{
  "os" : "Windows 10"
}

{
  "os" : "WINDOWS 8"
}

{
  "os" : "UBunTu 18.04"
}

how can I query on os with case insensitivity and contains using Spring MongoTemplate so that I can pass ["windows", "ubuntu"] and get all three documents from DB

I tried something like this but did not work.

String osRegEx = String.join(" | ", new String[]{"windows", "ubuntu"});
query.addCriteria(Criteria.where("os").regex(osRegEx, "i"));
3 Answers

It worked in this way...

String osRegEx = String.join("|", new String[]{"windows.*", "ubuntu.*"});
query.addCriteria(Criteria.where("os").regex("("+osRegEx+")", "i"));

I think you are facing this issue because of the string that you have provided for regex. You have Windows 10 etc in mongo with the version number but you are only having the regex string to match the windows/ubuntu part :

String osRegEx = String.join(" | ", new String[]{"windows.*", "ubuntu.*"});
query.addCriteria(Criteria.where("os").regex(osRegEx, "i"));

Here is a solution:

String [] queryStrs = { "windows", "ubuntu" };
String patternStr = Stream.of(queryStrs).collect(Collectors.joining("|", "(", ")"));
Pattern pattern = Pattern.compile(patternStr, Pattern.CASE_INSENSITIVE);

Criteria criteria = new Criteria().regex(pattern);
Query query = Query.query(criteria);
List<Foo> result = mongoTemplate.find(query, Foo.class);
Related