Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data MongoDB criteria with $in and list of regexes

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?

like image 477
ArturasJ Avatar asked Aug 05 '16 09:08

ArturasJ


1 Answers

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".

like image 104
Rutu Trivedi Avatar answered Nov 05 '22 00:11

Rutu Trivedi