In spring data mongodb how to achieve pagination for aggregation

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

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

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-06 00:16

    Here is my generic solution:

    public Page list(Pageable pageable) {
        // build your main stages
        List mainStages = Arrays.asList(match(....), group(....));
        return pageAggregation(pageable, mainStages, "target-collection", ResultObject.class);
    }
    
    public  Page pageAggregation(
            final Pageable pageable,
            final List mainStages,
            final String collection,
            final Class clazz) {
        final List stagesWithCount = new ArrayList<>(mainStages);
        stagesWithCount.add(count().as("count"));
        final Aggregation countAgg = newAggregation(stagesWithCount);
        final Long count = Optional
                .ofNullable(mongoTemplate.aggregate(countAgg, collection, Document.class).getUniqueMappedResult())
                .map(doc -> ((Integer) doc.get("count")).longValue())
                .orElse(0L);
    
        final List stagesWithPaging = new ArrayList<>(mainStages);
        stagesWithPaging.add(sort(pageable.getSort()));
        stagesWithPaging.add(skip(pageable.getOffset()));
        stagesWithPaging.add(limit(pageable.getPageSize()));
        final Aggregation resultAgg = newAggregation(stagesWithPaging);
        final List result = mongoTemplate.aggregate(resultAgg, collection, clazz).getMappedResults();
    
        return new PageImpl<>(result, pageable, count);
    }
    

提交回复
热议问题