In spring data mongodb how to achieve pagination for aggregation

前端 未结 7 1620
渐次进展
渐次进展 2021-02-05 23:32

In spring data mongodb using mongotemplate or mongorepository, how to achieve pagination for aggregateion

7条回答
  •  南旧
    南旧 (楼主)
    2021-02-06 00:11

    As per the answer https://stackoverflow.com/a/39784851/4546949 I wrote code for Java.

    Use aggregation group to get count and array of data with other paging information.

        AggregationOperation group = Aggregation.group().count().as("total")
                .addToSet(pageable.getPageNumber()).as("pageNumber")
                .addToSet(pageable.getPageSize()).as("pageSize")
                .addToSet(pageable.getOffset()).as("offset")
                .push("$$ROOT").as("data");
    

    Use Aggregation project to slice as per the paging information.

        AggregationOperation project = Aggregation.project()
                .andInclude("pageSize", "pageNumber", "total", "offset")
                .and(ArrayOperators.Slice.sliceArrayOf("data").offset((int) pageable.getOffset()).itemCount(pageable.getPageSize()))
                .as("data");
    

    Use mongo template to aggregate.

        Aggregation aggr = newAggregation(group, project);
        CustomPage page = mongoTemplate.aggregate(aggregation, Foo.class, CustomPage.class).getUniqueMappedResult();
    

    Create a CustomPage.

        public class CustomPage {
            private long pageSize;
            private long pageNumber;
            private long offset;
            private long total;
            private List data;
        }
    

提交回复
热议问题