问题描述
我将 spring-data mongo 与基于 JSON 的查询方法一起使用,但不确定如何在搜索查询中允许可选参数.
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
@Query("{ 'name' : {$regex : ?0, $options : 'i'}, 'createdDate' : {$gte : ?1, $lt : ?2 }} }")
List<MyItem> getItemsLikeNameByDateRange(String name, Date startDateRange, Date endDateRange);
-但我不想应用名称正则表达式匹配,或者如果将 NULL 值传递给方法,则不应用日期范围限制.
-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.
目前看来我可能必须使用 mongoTemplate 构建查询.
At the moment it looks like I might have to build the query using the mongoTemplate.
是否有任何替代方案 - 或者使用 mongoTemplate 是最佳选择?
Are there any alternatives - or is using mongoTemplate the best option?
谢谢
推荐答案
为了在布尔逻辑中实现这一点,我执行以下操作并转换为编程语言中可用的操作
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)
在普通的 SQL 中,这是这样完成的
In plain SQL, this is done as
where (null = :query) or (field = :query)
在 MongoDB 中,这是通过 $where 完成的
In MongoDB this is done through the $where
{ $where: '?0 == null || this.field == ?0' }
我们可以通过使用 Mongo 操作来加快速度一点,而不是以牺牲一些可读性为代价构建函数的所有内容.不幸的是,它不起作用.
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 } ] }
所以你拥有的是
@Query("{ $or : [ { $where: '?0 == null' } , { field : ?0 } ] }")
List<Something> findAll(String query, Pageable pageable);
这可以进一步扩展为处理 in/all 子句的数组
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);
这篇关于spring-data-mongo - 可选查询参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!