In spring data mongodb how to achieve pagination for aggregation

goutham picture goutham · Dec 23, 2015 · Viewed 13k times · Source

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

Answer

Fırat KÜÇÜK picture Fırat KÜÇÜK · May 16, 2017

In addition to ssouris solution you can use Pageable classes for the results.

public Page<UserListItemView> list(final Pageable pageable) {

    final Aggregation agg = newAggregation(
        skip(pageable.getPageNumber() * pageable.getPageSize()),
        limit(pageable.getPageSize())
    );

    final List<UserListItemView> results = mongoTemplate
        .aggregate(agg, User.class, UserListItemView.class)
        .getMappedResults();

    return new PageImpl<>(results, pageable, results.size())
}