spring-data-mongo - 可选的查询参数? [英] spring-data-mongo - optional query parameters?

查看:150
本文介绍了spring-data-mongo - 可选的查询参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用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中,这是以

where (null = :query) or (field = :query)

在MongoDB中,这是通过$ where

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 } ] } 

所以你拥有的是

@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 - 可选的查询参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆