I've spotted MongoDb functionality that allows to find elements by a list of regexes using $in. Example:
db.inventory.find( { tags: { $in: [ /^be/, /^st/ ] } } )
And it works perfectly when typed directly to some Mongo tool as a query.
Now I'm trying to apply this query using spring-data-mongodb version 1.8.4.RELEASE. Example code:
List<Pattern> regexList = Arrays.asList(Pattern.compile("\\b5\\b"), Pattern.compile("\\b8\\b")); //regexes to find numbers 5 or 8 in string
Query query = new Query();
query.addCriteria(Criteria.where("key").in(regexList));
And it does not find anything, because query looks like this:
{"key" : { "$in" : [ { "$regex" : "\\b5\\b"} , { "$regex" : "\\b8\\b"}]}}}
First problem is the "$regex" that is not allowed in "$in" queries. Second problem is quotation marks that envelops regexes. I've also tried passing string list, but with no success either.
Am I missing something?
I had the same issue and finally found the below solution.
Query query = new Query();
query.addCriteria(Criteria.where("key").regex(searchString));
No need to use $in. $regex can search in the string as well as in the list of String. To search case insensitive substring add option "i".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With