1. Introduction

When working with MongoDB in Spring Data, the MongoRepository interface provides a simple way to interact with MongoDB collections using built-in methods.

In this quick tutorial, we’ll learn how to use limit and skip in the MongoRepository.

2. Setup

First things first, let’s create a repository called StudentRepository. This is where we’ll store information about students:

public interface StudentRepository extends MongoRepository<Student, String> {}

Then, we add some sample student records to this repository. Think of these like practice data to help us play around and learn:

@Before
public void setUp() {
    Student student1 = new Student("A", "Abraham", 15L);
    Student student2 = new Student("B", "Usman", 30L);
    Student student3 = new Student("C", "David", 20L);
    Student student4 = new Student("D", "Tina", 45L);
    Student student5 = new Student("E", "Maria", 33L);

    studentList = Arrays.asList(student1, student2, student3, student4, student5);
    studentRepository.saveAll(studentList);
}

After that, we will dive into the details of using skip and limit to find specific student information.

3. Using Aggregation Pipeline

An aggregation pipeline is a powerful tool for processing, transforming, and analyzing data. It works by chaining together multiple stages, each performing a specific operation. These operations include filtering, grouping, sorting, pagination, and more.

Let’s apply the limit and skip to a basic example:

@Test
public void whenRetrievingAllStudents_thenReturnsCorrectNumberOfRecords() {
    // WHEN
    List<Student> result = studentRepository.findAll(0L, 5L);
    // THEN
    assertEquals(5, result.size());
}

The above aggregation pipeline skips the specified number of documents and limits the output to the specified number.

@Test
public void whenLimitingAndSkipping_thenReturnsLimitedStudents() {
    // WHEN
    List<Student> result = studentRepository.findAll(3L, 2L);
    // THEN
    assertEquals(2, result.size());
    assertEquals("Tina", result.get(0).getName());
    assertEquals("Maria", result.get(1).getName());
}

We can even apply limit and skip in a complex aggregation pipeline as well:

@Aggregation(pipeline = {
  "{ '$match': { 'id' : ?0 } }",
  "{ '$sort' : { 'id' : 1 } }",
  "{ '$skip' : ?1 }",
  "{ '$limit' : ?2 }"
})
List<Student> findByStudentId(final String studentId, Long skip, Long limit);

Here’s the test:

@Test
public void whenFilteringById_thenReturnsStudentsMatchingCriteria() {
    // WHEN
    List<Student> result = studentRepository.findByStudentId("A", 0L, 5L);
    // THEN
    assertEquals(1, result.size());
    assertEquals("Abraham", result.get(0).getName());
}

4. Using Pageable

In Spring Data, a Pageable is an interface that represents a request to retrieve data in a paginated manner. When querying data from MongoDB collection, a Pageable object allows us to specify parameters such as page number, page size, and sorting criteria. This is particularly useful for displaying large datasets on applications where showing all items at once would be slow.

Let’s explore how defining a repository method with Pageable enables efficient data retrieval:

Page<Student> findAll(Pageable pageable);

Let’s add a test:

@Test
public void whenFindByStudentIdUsingPageable_thenReturnsPageOfStudents() {
    // GIVEN
    Sort sort = Sort.by(Sort.Direction.DESC, "id");
    Pageable pageable = PageRequest.of(0, 5, sort);

    // WHEN
    Page<Student> resultPage = studentRepository.findAll(pageable);

    // THEN
    assertEquals(5, resultPage.getTotalElements());
    assertEquals("Maria", resultPage.getContent().get(0).getName());
}

5. Conclusion

In this short article, we’ve explored the utilization of skip and limit functionalities within MongoRepository. Moreover, we’ve highlighted the utility of Pageable for streamlined pagination and the flexibility of @Aggregation for more control over the query logic or specific filtering needs.

As always, all the code snippets can be found over on GitHub.

Course – LSD (cat=Persistence)

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:

>> CHECK OUT THE COURSE
res – Persistence (eBook) (cat=Persistence)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.