Spring Boot MongoDB查询$match阶段如何自动排除空值对应筛选字段
Spring Boot MongoDB动态忽略空值查询解决方案
你当前的硬编码写法将所有匹配条件固定写在$and逻辑中,无论传入的参数是否为空,所有条件都会执行校验,无法实现空值自动忽略的需求,可通过以下两种方案解决:
方案1:基于@Aggregation注解+SpEL动态条件
无需修改方法定义,直接在聚合注解中通过Spring Expression Language动态判断参数是否为空,空值时返回恒成立条件跳过筛选:
@Aggregation(pipeline = { """ { $match: { $and: [ #{ #name != null && !#name.isEmpty() ? {name: #name} : {_id: {$exists: true}} }, #{ #csi != null && !#csi.isEmpty() ? {csi: #csi} : {_id: {$exists: true}} }, #{ #city != null && !#city.isEmpty() ? {city: #city} : {_id: {$exists: true}} } ] } } """ }) List<Data> getdata(String name, String csi, String city);
说明:当参数为空时,逻辑会自动替换为{_id: {$exists: true}}这个永远成立的条件,不会对查询结果产生任何影响,等价于忽略该字段的筛选。
方案2:基于MongoTemplate手动构造聚合(更灵活)
如果后续需要新增筛选条件、或者扩展其他聚合阶段,推荐用MongoTemplate手动构造动态查询,逻辑更清晰易维护:
import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.aggregation.Aggregation; import org.springframework.data.mongodb.core.aggregation.AggregationOperation; import org.springframework.stereotype.Repository; import java.util.ArrayList; import java.util.List; import static org.springframework.data.mongodb.core.query.Criteria.where; @Repository public class CustomDataRepository { private final MongoTemplate mongoTemplate; // 构造注入MongoTemplate public CustomDataRepository(MongoTemplate mongoTemplate) { this.mongoTemplate = mongoTemplate; } public List<Data> getdata(String name, String csi, String city) { List<AggregationOperation> ops = new ArrayList<>(); // 动态添加匹配条件,空值直接跳过不添加 if (name != null && !name.isBlank()) { ops.add(Aggregation.match(where("name").is(name))); } if (csi != null && !csi.isBlank()) { ops.add(Aggregation.match(where("csi").is(csi))); } if (city != null && !city.isBlank()) { ops.add(Aggregation.match(where("city").is(city))); } // 可继续添加其他聚合阶段,比如分组、排序、分页等 // ops.add(Aggregation.group("city").count().as("total")); Aggregation aggregation = Aggregation.newAggregation(ops); // 替换为你实际的集合名称 return mongoTemplate.aggregate(aggregation, "你的集合名", Data.class).getMappedResults(); } }
注意事项
- 两种方案都兼容null和空字符串两种空值场景,按需调整空值判断逻辑即可
- 如果你的聚合逻辑还有其他阶段,直接在对应位置补充配置即可
内容的提问来源于stack exchange,提问作者rakesh kandukuri
相关产品推荐
相关产品推荐

