【问题标题】:spring-data-mongo - optional query parameters?spring-data-mongo - 可选查询参数?
【发布时间】:2012-07-21 17:51:14
【问题描述】:

我将 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 是最佳选择?

谢谢

【问题讨论】:

  • 现在我已经走上了使用 Criteria 类的路线。它看起来确实比在注解中嵌入 JSON 查询更简洁,并且更容易自定义检索哪些字段。

标签: java spring mongodb spring-data spring-data-mongodb


【解决方案1】:

为了在布尔逻辑中实现这一点,我执行以下操作并将其转换为编程语言中可用的操作

: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);

【讨论】:

  • 如果您的查询参数是 Date 类型,您必须像这样编写 $where 部分才能工作:{ $where: '\\'?0\\' == \\'null\\'' }
  • 不幸的是,这不适用于页面结果,因为 count 命令中不允许使用 $where。我必须编写一个自定义查询方法来获取匹配文档的数量。
【解决方案2】:

除了阿基米德的回答:
如果您需要匹配文档的计数,请将$where 替换为$expr

@Query("{ $or : [ { $expr: { $eq: ['?0', 'null'] } } , { field : ?0 } ] }")
Page<Something> findAll(String query, Pageable pageable);

【讨论】:

    猜你喜欢
    • 2013-05-20
    • 2015-12-20
    • 2018-08-16
    • 2022-01-17
    • 1970-01-01
    • 2020-01-08
    • 2017-05-02
    • 1970-01-01
    相关资源
    最近更新 更多