Spring Boot MongoTemplate聚合查询如何将返回结果转为List<CommentDto>
实现方案
方案1:通过临时接收类直接获取(推荐,代码改动最小)
你当前的聚合查询返回的是包含_id和comments的单条结构,只需要定义一个临时的结果接收类,即可直接拿到转换好的List<CommentDto>:
- 先定义临时聚合结果类
import lombok.Data; import java.util.List; @Data public class PostCommentResult { // 字段名要和聚合返回的comments字段名完全对应 private List<CommentDto> comments; }
- 修改原有聚合代码的返回类型
MatchOperation matchOperation = Aggregation.match( Criteria.where("_id").is(new ObjectId(postId)) ); ProjectionOperation projectionOperation = Aggregation.project() .and("comments").as("comments"); Aggregation aggregation = Aggregation.newAggregation(matchOperation, projectionOperation); // 替换原来的Object.class为自定义的PostCommentResult.class AggregationResults<PostCommentResult> result = mongoTemplate.aggregate(aggregation, PostEntity.class, PostCommentResult.class); // 因为是按主键查询,只有一条结果,直接取唯一结果的comments字段即可 List<CommentDto> commentDtoList = result.getUniqueMappedResult().getComments();
方案2:拆分数组直接映射CommentDto(不需要定义临时类)
如果不想额外定义临时类,可以在聚合中加入$unwind操作拆分comments数组,直接将每个子文档映射为CommentDto:
MatchOperation matchOperation = Aggregation.match( Criteria.where("_id").is(new ObjectId(postId)) ); // 将comments数组拆分为多条独立文档 UnwindOperation unwindOperation = Aggregation.unwind("comments"); // 将comments下的字段映射为根级字段,和CommentDto的属性一一对应 ProjectionOperation projectionOperation = Aggregation.project() .and("comments._id").as("_id") .and("comments.writer").as("writer") .and("comments.nickname").as("nickname") .and("comments.createDate").as("createDate") .and("comments.content").as("content") .and("comments.replies").as("replies") .and("comments.likes").as("likes"); Aggregation aggregation = Aggregation.newAggregation(matchOperation, unwindOperation, projectionOperation); // 直接用CommentDto作为返回类型 AggregationResults<CommentDto> result = mongoTemplate.aggregate(aggregation, PostEntity.class, CommentDto.class); List<CommentDto> commentDtoList = result.getMappedResults();
注意事项
- 确保
CommentDto的字段名和MongoDB中存储的字段名完全一致,如果有命名差异可以在CommentDto的对应属性上添加@org.springframework.data.mongodb.core.mapping.Field("数据库字段名")注解指定映射关系 - 如果
CommentDto和数据库存储的Comment结构有差异,可以先查询出Comment实体类,再通过MapStruct等工具转换为Dto
内容的提问来源于stack exchange,提问作者hanjiman
相关产品推荐
相关产品推荐

