使用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
相关产品推荐
相关产品推荐

