Last active
June 20, 2024 08:19
-
-
Save ilkerkocatepe/caee114e2502fe2f16541010d0c567fa to your computer and use it in GitHub Desktop.
Spring Boot - MongoDB - Page Aggregation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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