Home > Net >  I want to change the return type of AggregationResults
I want to change the return type of AggregationResults

Time:11-13

I'm currently using mongoTemplate via Spring boot and my data structure is:

enter image description here

I wrote the following code to get only the comments list in the db.

        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);

The contents of System.out::println are as follows.

{
    _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=[]
        },
        ...
    ]
}

The data is imported fine, but I don't know how to process it. I want to create a CommentDto object and put the above output comments list in List<CommentDto>, how should I do it?

CodePudding user response:

When you run the query you are mapping to Object. Just change the output object type to your dto:

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

CodePudding user response:

You could also retrieve it as a List:

Aggregation aggregation = Aggregation.newAggregation(lookUp, match1, unwindPrices, unwindTags, unwindIndex, match2, groupOperation);

List<ProductVo> list = mongotemplate.aggregate(aggregation ,"products", ProductVo.class).getMappedResults();
  • Related