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

Spring Data MongoDB聚合查询分组字段无法映射到POJO属性如何解决

问题原因
  • MongoDB的group聚合阶段会把所有分组字段打包放入返回结果的_id复合字段中,不会直接返回为顶层字段,因此Spring Data映射时只会把复合结构赋值给Location类的_id属性,无法自动映射到独立的countryCode、countryName字段。
解决方案

你只需要在聚合逻辑中追加project阶段,把_id下的字段提取为顶层字段即可,修改后的代码如下:

@Repository
public class AggregateQueryRepository {
    
    @Autowired
    ReactiveMongoTemplate reactiveMongoTemplate;
 
    public Flux<Location> getAllCountryCodeAndCountry() {
        Aggregation aggregation = newAggregation(
                // 原分组逻辑不变
                group("countryCode", "countryName"),
                // 新增字段映射阶段
                project()
                        .and("_id.countryCode").as("countryCode")
                        .and("_id.countryName").as("countryName")
                        // 不需要返回_id字段可直接用andExclude("_id"),若要求_id为null用下面这句
                        .andLiteral(null).as("_id")
        );
        return reactiveMongoTemplate.aggregate(aggregation, "location", Location.class);
    }
}
注意事项
  • 请确保Location类的countryCode、countryName字段有公开的getter/setter方法,或添加了Lombok的@Data注解,保证Spring Data可以正常完成属性映射。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 10:24:03