我将 spring-data mongo 与基于 JSON 的查询方法一起使用,但不确定如何在搜索查询中允许可选参数。
例如 - 假设我有以下功能
@Query("{ 'name' : {$regex : ?0, $options : 'i'}, 'createdDate' : {$gte : ?1, $lt : ?2 }} }")
List<MyItem> getItemsLikeNameByDateRange(String name, Date startDateRange, Date endDateRange);
-但我不想应用名称正则表达式匹配,或者如果将 NULL 值传递给方法,则不应用日期范围限制。
目前看来我可能必须使用 mongoTemplate 构建查询。
是否有任何替代方案 - 或者使用 mongoTemplate 是最佳选择?
谢谢
最佳答案
为了在 boolean 逻辑中实现这一点,我执行以下操作并将其转换为编程语言中可用的操作
:query != null -> field == :query
!(:query != null) || (field == :query)
(:query == null) || (field == :query)
在普通的 SQL 中,这是这样完成的
where (null = :query) or (field = :query)
在 MongoDB 中,这是通过 $where 完成的
{ $where: '?0 == null || this.field == ?0' }
我们可以通过使用 Mongo Operations 来加快速度一点,而不是以牺牲一些可读性为代价构建函数的所有内容。不幸的是,它不起作用。
{ $or : [ { $where: '?0 == null' } , { field : ?0 } ] }
所以你拥有的是
@Query("{ $or : [ { $where: '?0 == null' } , { field : ?0 } ] }")
List<Something> findAll(String query, Pageable pageable);
这可以进一步扩展为处理 in/all 子句的数组
@Query("{ $or : [ { $where: '?0.length == 0' } , { field : { $in : ?0 } } ] }")
List<Something> findAll(String query, Pageable pageable);
关于java - spring-data-mongo - 可选查询参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11613464/