And*_*w B 17 java spring mongodb spring-data
我使用spring-data mongo和基于JSON的查询方法,并且不确定如何在搜索查询中允许可选参数.
例如 - 说我有以下功能
@Query("{ 'name' : {$regex : ?0, $options : 'i'}, 'createdDate' : {$gte : ?1, $lt : ?2 }} }")
List<MyItem> getItemsLikeNameByDateRange(String name, Date startDateRange, Date endDateRange);
Run Code Online (Sandbox Code Playgroud)
- 但我不想应用名称正则表达式匹配,或者如果将NULL值传递给方法,则不应用日期范围限制.
目前,我可能不得不使用mongoTemplate构建查询.
有没有其他选择 - 或者使用mongoTemplate是最佳选择?
谢谢
Arc*_*ano 20
要在布尔逻辑中实现此功能,我将执行以下操作并转换为编程语言中可用的操作
:query != null -> field == :query
!(:query != null) || (field == :query)
(:query == null) || (field == :query)
Run Code Online (Sandbox Code Playgroud)
在纯SQL中,这是完成的
where (null = :query) or (field = :query)
Run Code Online (Sandbox Code Playgroud)
在MongoDB中,这是通过$ where来完成的
{ $where: '?0 == null || this.field == ?0' }
Run Code Online (Sandbox Code Playgroud)
我们可以通过使用Mongo Operations 来加速这一点,而不是以牺牲一些可读性为代价来构建函数.不幸的是不起作用.
{ $or : [ { $where: '?0 == null' } , { field : ?0 } ] }
Run Code Online (Sandbox Code Playgroud)
所以你拥有的是
@Query("{ $or : [ { $where: '?0 == null' } , { field : ?0 } ] }")
List<Something> findAll(String query, Pageable pageable);
Run Code Online (Sandbox Code Playgroud)
这可以进一步扩展以处理in/all子句的数组
@Query("{ $or : [ { $where: '?0.length == 0' } , { field : { $in : ?0 } } ] }")
List<Something> findAll(String query, Pageable pageable);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11083 次 |
| 最近记录: |