Spring data mongo pagination Spring data mongo pagination mongodb mongodb

Spring data mongo pagination


You do not need to implement the method as when you autowired the Spring object PagingAndSortingRepository, it automatically implements the method for you.

Please note that since you are using Mongodb, you can extend MongoRepository instead.

Then in Spring, enable pagination using this:

@RequestMapping(value="INSERT YOUR LINK", method=RequestMethod.GET)  public List<Profile> getAll(int page) {    Pageable pageable = new PageRequest(page, 5); //get 5 profiles on a page    Page<Profile> page = repo.findAll(pageable);    return Lists.newArrayList(page);


I got it working by writing my own implementations, something like this:

List<Story> stories = null;Query query = new Query();query.with(pageable);stories = getTemplate().find(query, Story.class);long total = getTemplate().count(query, Story.class);Page<Story> storyPage = new PageImpl<Story>(stories, pageable, total);return storyPage;

I'm working with spring data & mongodb, using mongo template to query data.


In Spring Data, you create an interface and add a method using the naming conventions used by Spring data and the framework will generate the implementation of that method.To implement pagination, i create this method declaration in my repository:

public interface PersonRepository extends MongoRepository<Person, ObjectId> {    Page<Person> findByName(String name, Pageable pageable);}

Then, in my service i call this method like this:

Page<Person> persons = personRepository.findByName("Alex", PageRequest.of(0, 100));

Here, the page will contain 100 element.