You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅通过Spring Data Mongo Repository的@Query注解实现聚合查询(无需MongoTemplate)

在Spring Data MongoDB Repository中实现聚合去重的国家城市组合

没问题,我来帮你搞定这个需求——用Spring Data的Mongo Repository(不用MongoTemplate),通过@Query注解结合聚合操作实现国家和城市组合的去重。

首先,先纠正一下你原来@Query里的小问题:聚合操作是管道数组,每个阶段(比如$group、$project)是数组里的独立对象,而且MongoDB的语法里是冒号:不是等号=,比如_id: 0而不是_id=0。

下面是完整的实现步骤:

1. 定义对应的实体类

先创建和你的集合字段匹配的实体类,比如叫Employee:

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

@Document(collection = "employees")
public class Employee {
    private String emp_country;
    private String emp_city;

    // 构造函数、getter、setter按需实现
    public Employee() {}

    public Employee(String emp_country, String emp_city) {
        this.emp_country = emp_country;
        this.emp_city = emp_city;
    }

    // getter和setter方法
    public String getEmp_country() {
        return emp_country;
    }

    public void setEmp_country(String emp_country) {
        this.emp_country = emp_country;
    }

    public String getEmp_city() {
        return emp_city;
    }

    public void setEmp_city(String emp_city) {
        this.emp_city = emp_city;
    }
}

2. 编写带聚合查询的Repository接口

在你的Repository接口里,用@Query注解定义聚合管道,实现去重逻辑:

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

public interface EmployeeRepository extends MongoRepository<Employee, String> {

    @Query(value = "[ " +
            "   { '$group': { '_id': { 'emp_country': '$emp_country', 'emp_city': '$emp_city' } } }, " +
            "   { '$project': { 'emp_country': '$_id.emp_country', 'emp_city': '$_id.emp_city', '_id': 0 } } " +
            "]")
    List<Employee> findDistinctCountryCityPairs();
}

代码解释:

  • $group阶段:把emp_country和emp_city的组合作为分组的_id,MongoDB会自动把相同组合的文档归为一组,这样就完成了去重。
  • $project阶段:把分组_id里的字段提取出来,并且移除默认的_id字段,让返回的结构和Employee实体类匹配,这样Spring Data能正确映射结果。

3. 调用Repository方法获取结果

在你的业务代码里注入EmployeeRepository,调用findDistinctCountryCityPairs()方法就能得到你想要的去重后的国家城市组合:

// 示例Service层代码
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class EmployeeService {
    private final EmployeeRepository employeeRepository;

    public EmployeeService(EmployeeRepository employeeRepository) {
        this.employeeRepository = employeeRepository;
    }

    public List<Employee> getDistinctCountryCityCombinations() {
        return employeeRepository.findDistinctCountryCityPairs();
    }
}

这样执行后,返回的结果就和你期望的一致啦:

[ 
  { "emp_country":"country1", "emp_city":"city1" }, 
  { "emp_country":"country1", "emp_city":"city2" } 
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 10:09:08