我正在使用spring data mongo和基于JSON的查询方法,不确定如何在搜索查询中允许可选参数.

例如,假设我有以下功能

@Query("{ 'name' : {$regex : ?0, $options : 'i'}, 'createdDate' : {$gte : ?1, $lt : ?2 }} }")
List<MyItem> getItemsLikeNameByDateRange(String name, Date startDateRange, Date endDateRange);

-但我不想应用名称regex match,或者在向方法传递NULL值时不应用日期范围限制.

目前看来,我可能需要使用mongoTemplate构建查询.

有其他 Select 吗?或者使用mongoTemplate是最佳 Select 吗?

谢谢

推荐答案

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

: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操作,而不是以牺牲可读性为代价构建函数的所有内容,我们可以将速度提高a little.不幸的是,它不起作用.

{ $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);

Mongodb相关问答推荐

在mongo聚合管道的组阶段排除字段,但在最后将其包含在内

mongodb.将文档分组在数组中,对它们进行评分计数和求和并添加新字段

错误起草的 MongoDB 聚合管道 $match 阶段

如何 db.getUser() 使用 go mongo-driver

MongoDB聚合 - 用另一个数组过滤数组

MongoDB:使用数组过滤器进行更新插入

更新 mongodb 文档中的特定字段

.save() 不是函数 Mongoose

MongoDB:按标签获取文档

你如何在 Kubernetes 上设置 Mongo 副本集?

mongodb 中的 --bindip 配置选项有什么作用?

Mongodb:查询嵌套在数组中的json对象

Java MongoDB/BSON 类混淆

C# mongodb driver 2.0 - 如何在批量操作中更新插入?

直接从 URL 查询字符串提供的 mongo 查询有多危险?

MongoDB的数据库管理工具

无法将 Mongoose 连接到 Atlas

将新值推送到 mongodb 内部数组 - mongodb/php

Mongoose 为所有嵌套对象添加 _id

Mongo 条件为key doesn't exist?