Skip to content

Instantly share code, notes, and snippets.

@ilkerkocatepe
Last active June 20, 2024 08:19
Show Gist options
  • Save ilkerkocatepe/caee114e2502fe2f16541010d0c567fa to your computer and use it in GitHub Desktop.
Save ilkerkocatepe/caee114e2502fe2f16541010d0c567fa to your computer and use it in GitHub Desktop.
Spring Boot - MongoDB - Page Aggregation
public <T> Page<T> pageAggregation(
final Pageable pageable,
final Criteria criteria,
final String collection,
final Class<T> clazz) {
long count;
if (criteria.getCriteriaObject().isEmpty()) {
count = Optional
.of(mongoTemplate.estimatedCount(clazz))
.orElse(0L);
} else {
count = Optional
.of(mongoTemplate.count(new org.springframework.data.mongodb.core.query.Query(criteria), clazz))
.orElse(0L);
}
final List<AggregationOperation> stagesWithPaging = new ArrayList<>();
stagesWithPaging.add(Aggregation.match(criteria));
stagesWithPaging.add(sort(pageable.getSort()));
stagesWithPaging.add(skip(pageable.getOffset()));
stagesWithPaging.add(limit(pageable.getPageSize()));
final Aggregation resultAgg = newAggregation(stagesWithPaging);
final List<T> result = mongoTemplate.aggregate(resultAgg, collection, clazz).getMappedResults();
return new PageImpl<>(result, pageable, count);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment