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

使用MongoTemplate进行MongoDB聚合查询时分组字段name返回null

问题原因及解决方案

问题根源

在MongoDB聚合的group阶段,按name字段分组后,分组键会被存储在_id字段中,而非保留原name字段。你后续的project阶段直接读取name字段,自然会返回null——此时文档结构里已不存在这个字段。

修正后的聚合代码

修改project阶段,将_id字段的值映射为name:

Aggregation aggregation = Aggregation.newAggregation(
        Aggregation.match(Criteria.where("modality").is("check")),
        Aggregation.group("name").count().as("check_count"),
        // 将分组标识_id(即原name的值)映射为name字段,同时保留check_count
        Aggregation.project().and("_id").as("name").and("check_count").as("check_count")
);
AggregationResults<Response> res = mongoTemplate.aggregate(aggregation, "user", Response.class);

额外优化建议

你的Response类中check_count定义为string类型,但聚合返回的count是整数类型,建议改为数值类型避免类型转换异常:

class Response{
    private String name;
    // 改为Integer或Long类型
    private Integer check_count;

    // constructor and get/set
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 09:41:12