spring-data-mongo - optional query parameters?
In addition to Archimedes's answer:
If you need the count of matched documents, replace $where
with $expr
.
@Query("{ $or : [ { $expr: { $eq: ['?0', 'null'] } } , { field : ?0 } ] }")
Page<Something> findAll(String query, Pageable pageable);
To implement this in Boolean logic I do the following and the conversion to operations that are available in programming languages
:query != null -> field == :query
!(:query != null) || (field == :query)
(:query == null) || (field == :query)
In plain SQL, this is done as
where (null = :query) or (field = :query)
In MongoDB this is done through the $where
{ $where: '?0 == null || this.field == ?0' }
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.
{ $or : [ { $where: '?0 == null' } , { field : ?0 } ] }
So what you have is
@Query("{ $or : [ { $where: '?0 == null' } , { field : ?0 } ] }")
List<Something> findAll(String query, Pageable pageable);
This can be further expanded to handle arrays for in/all clauses
@Query("{ $or : [ { $where: '?0.length == 0' } , { field : { $in : ?0 } } ] }")
List<Something> findAll(String query, Pageable pageable);