【问题标题】:I want to change the return type of AggregationResults我想更改 AggregationResults 的返回类型
【发布时间】:2021-12-24 15:03:24
【问题描述】:

我目前正在通过 Spring boot 使用mongoTemplate,我的数据结构是:

我写了下面的代码只获取db中的cmets列表。

        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);
        AggregationResults<Object> result = mongoTemplate.aggregate(aggregation, PostEntity.class, Object.class);
        result.getMappedResults().forEach(System.out::println);

System.out::println的内容如下。

{
    _id=618b37bfb6196619dbe35abb, 
    comments=[
        {
            _id=618b65c64d04820f90565c70, 
            writer=617a2d81c4033d1358e2ffba, 
            nickname=test user, 
            createDate=Wed Nov 10 15:25:10 KST 2021, 
            content=qwer, 
            replies=[], 
            likes=[]
        }, 
        {
            _id=618b66784d04820f90565c71, 
            writer=617a2d81c4033d1358e2ffba, 
            nickname=test user2, 
            createDate=Wed Nov 10 15:28:08 KST 2021, 
            content=asdf, 
            replies=[], 
            likes=[]
        }, 
        {
            _id=618b67d54d04820f90565c72, 
            writer=617a2d81c4033d1358e2ffba, 
            nickname=test user3, 
            createDate=Wed Nov 10 15:33:57 KST 2021, 
            content=asdf, 
            replies=[], 
            likes=[]
        },
        ...
    ]
}

数据导入正常,但不知道如何处理。我想创建一个CommentDto对象,把上面输出的cmets列表放到List&lt;CommentDto&gt;,应该怎么做呢?

【问题讨论】:

    标签: spring-boot aggregation mongotemplate


    【解决方案1】:

    您也可以将其作为列表检索:

    Aggregation aggregation = Aggregation.newAggregation(lookUp, match1, unwindPrices, unwindTags, unwindIndex, match2, groupOperation);
    
    List<ProductVo> list = mongotemplate.aggregate(aggregation ,"products", ProductVo.class).getMappedResults();
    

    【讨论】:

      【解决方案2】:

      当您运行查询时,您将映射到 Object。只需将输出对象类型更改为您的 dto:

      AggregationResults<CommentDto> result = mongoTemplate.aggregate(aggregation, PostEntity.class, CommentDto.class);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-30
        • 1970-01-01
        • 2019-07-03
        • 2021-05-01
        • 2013-07-04
        • 1970-01-01
        • 1970-01-01
        • 2021-06-22
        相关资源
        最近更新 更多