spring-data-mongo - optional query parameters?

前端 未结 2 750
北荒
北荒 2020-12-05 03:15

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 foll

相关标签:
2条回答
  • 2020-12-05 03:54

    You might be interested in providing feedback or vote on this issue: https://jira.springsource.org/browse/DATAJPA-209

    It deals with exactly this problem., except for SD JPA. Seems like it'd be appropriate for many other SD subprojects.

    0 讨论(0)
  • 2020-12-05 04:00

    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);
    
    0 讨论(0)
提交回复
热议问题