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

Spring Boot中MongoTemplate实现MongoDB聚合查询等效代码求助

Spring Boot中MongoTemplate实现等效MongoDB聚合查询

先定义结果映射类

为了方便接收聚合结果,需要创建两个简单的POJO:

// 存储单种传真类型的统计数据
class FaxTypeCount {
    private String faxType;
    private Integer count;

    public FaxTypeCount(String faxType, Integer count) {
        this.faxType = faxType;
        this.count = count;
    }

    // 省略getter、setter方法
}

// 存储每个邮箱的总统计数据
class EmailFaxStats {
    private String email;
    private List<FaxTypeCount> faxTypes;
    private Integer count;

    public EmailFaxStats(String email, List<FaxTypeCount> faxTypes, Integer count) {
        this.email = email;
        this.faxTypes = faxTypes;
        this.count = count;
    }

    // 省略getter、setter方法
}

完整聚合代码实现

// 1. 第一步分组:按email和faxType组合分组,统计每组传真数量
GroupOperation groupByEmailAndFaxType = Aggregation.group("email", "faxType")
        .count().as("faxCount");

// 2. 第二步分组:按第一步分组结果中的_id.email分组,组装传真类型统计数组并计算总数
GroupOperation groupByEmail = Aggregation.group("_id.email")
        // 构造嵌套对象并推入faxTypes数组
        .push(new BasicDBObject("faxType", "$_id.faxType")
                .append("count", "$faxCount"))
        .as("faxTypes")
        // 累加每组的传真数量得到总数
        .sum("$faxCount").as("count");

// 3. 按总数量降序排序
SortOperation sortByCountDesc = Aggregation.sort(Sort.Direction.DESC, "count");

// 4. 限制返回前2条数据
LimitOperation limitTo2 = Aggregation.limit(2);

// 5. 投影:截取faxTypes数组前2个元素,同时将_id重命名为email
ProjectionOperation projectFields = Aggregation.project("count")
        .and("faxTypes").slice(2).as("faxTypes")
        .and("_id").as("email");

// 组装聚合管道
Aggregation aggregation = Aggregation.newAggregation(
        groupByEmailAndFaxType,
        groupByEmail,
        sortByCountDesc,
        limitTo2,
        projectFields
);

// 执行聚合查询,替换成你的集合名称
List<EmailFaxStats> result = mongoTemplate.aggregate(aggregation, "你的集合名", EmailFaxStats.class).getMappedResults();

关键说明

  • 引用第一个分组的_id.email:直接用字符串"_id.email"作为第二步分组的键即可,Spring Data MongoDB会自动识别嵌套字段路径。
  • 构造嵌套push对象:通过BasicDBObject模拟原MongoDB语句中$push的嵌套结构,确保和原生聚合逻辑一致。
  • 投影阶段重命名_id:将分组后的_id(即邮箱地址)重命名为email,方便映射到POJO的对应字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 09:57:46