Spring - Pagination with MongoTemplate


By default, spring mongo template has no pagination functionality. It searches, and returns the query as a list of records: for example if we are looking for the list of Articles using the criteria:

mongoTemplate.find(Query.query(Criteria.where("...").is(...)), Article.class);

By using the Pageable class we can do the pagination:

Pageable pageable = PageRequest.of(pageNumber, itemsPerPage);
mongoTemplate.find(Query.query(Criteria.where("...").is(...)).with(pageable), Article.class);