Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to query case insensitivity and contains with Spring MongoTemplate

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"));
like image 450
MAHIE Avatar asked Sep 02 '25 10:09

MAHIE


1 Answers

It worked in this way...

String osRegEx = String.join("|", new String[]{"windows.*", "ubuntu.*"});
query.addCriteria(Criteria.where("os").regex("("+osRegEx+")", "i"));
like image 100
MAHIE Avatar answered Sep 04 '25 09:09

MAHIE