You need to enable JavaScript to run this app. 如何实现带过滤条件的MongoDB Distinct去重查询
优惠活动
大模型
产品
解决方案
定价
更多

如何实现带过滤条件的MongoDB Distinct去重查询

基于Spring Data MongoDB(类JPA Repository风格)的带过滤Distinct查询实现

你此前基于MongoTemplate写的原生实现可以正常运行,完全可以通过Spring Data MongoDB提供的Repository(即Mongo场景下的JPA风格接口)实现同等逻辑,无需直接操作底层集合对象,具体实现步骤如下:

前置依赖准备

首先定义与alertStatus集合结构对应的文档实体类:

import org.springframework.data.mongodb.core.mapping.Document;
import lombok.Data;

@Data
@Document("alertStatus")
public class AlertStatus {
    // 对应文档中的id字段
    private Long id;
    private String group;
    private String state;
}

核心实现写法

1. 派生式查询方法(零代码实现,最贴合JPA使用习惯)

定义对应Repository接口,继承MongoRepository接口,直接按照Spring Data的方法命名规则编写查询方法即可,无需手动实现逻辑:

import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;

public interface AlertStatusRepository extends MongoRepository<AlertStatus, Long> {
    // 方法规则:findDistinct<查询字段>By<过滤条件字段>
    // 作用:查询满足state等于入参的文档,返回去重后的group值列表
    List<String> findDistinctGroupByState(String state);
}

直接在业务类中注入该Repository即可调用,执行效果和你此前写的MongoTemplate代码完全一致:

@Service
public class AlertStatusService {
    @Autowired
    private AlertStatusRepository alertStatusRepository;

    public void logPendingGroups() {
        List<String> pendingGroups = alertStatusRepository.findDistinctGroupByState("PENDING");
        pendingGroups.forEach(g -> log.info(g));
    }
}

2. @Query注解自定义查询(适配复杂场景)

如果后续过滤条件更复杂,不适合通过方法名派生,可以在Repository方法上通过@Query注解直接编写Mongo过滤语句,同样是JPA风格的接口写法,不需要引入MongoTemplate:

public interface AlertStatusRepository extends MongoRepository<AlertStatus, Long> {
    // 方法名保留Distinct标识,框架自动识别为去重查询
    @Query(value = "{ 'state': ?0 }", fields = "{ 'group': 1, '_id': 0 }")
    List<String> findDistinctGroupByState(String state);
}

Spring Data会自动识别方法名上的Distinct关键字,将查询转换为Mongo原生distinct命令执行,最终返回去重后的结果集。

补充说明

  • 该Repository风格的接口完全遵循JPA的使用范式,所有查询逻辑由Spring Data框架自动生成底层Mongo语句,无需手动维护集合连接、文档转换逻辑
  • 如果后续需要扩展过滤条件,直接在方法名后追加对应规则即可,比如需要同时过滤state=PENDING且group不为空的场景,只需将方法改为findDistinctGroupByStateAndGroupIsNotNull(String state)即可,不需要修改任何实现代码
  • 性能层面和你直接操作MongoTemplate的原生实现无差异,框架会在生成查询时直接调用MongoDB原生的distinct命令完成数据处理

内容的提问来源于stack exchange,提问作者disk91

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.11 15:15:08