Skip to content
Advertisement

spring-data-mongo – optional query parameters?

I am using spring-data mongo with the JSON based query methods, and am unsure how to allow optional parameters in a search query.

For instance – say I had the following function

JavaScript

-but I didnt want to apply the name regex match, or not apply a date range restriction if NULL values were passed to the method.

At the moment it looks like I might have to build the query using the mongoTemplate.

Are there any alternatives – or is using mongoTemplate the best option?

Thanks

Advertisement

Answer

To implement this in Boolean logic I do the following and the conversion to operations that are available in programming languages

JavaScript

In plain SQL, this is done as

JavaScript

In MongoDB this is done through the $where

JavaScript

We can speed this up a little by using Mongo Operations rather than building everything to the function at the expense of some readability. does not work unfortunately.

JavaScript

So what you have is

JavaScript

This can be further expanded to handle arrays for in/all clauses

JavaScript
Advertisement