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

