Home » Framework » Pagination in Spring Boot application with MongoDB

Pagination in Spring Boot application with MongoDB

In this article let us see how to do pagination in the Spring Boot application with MongoDB as a database. Let us see the below things one by one.

What is pagination?

Pagination is the process of splitting the data with the pages. Each page holds the records based on the record size we want.

Generally, pagination is effective if it happens on the server-side. The server-side pagination produces the pages with records based on the page number and records size. This increases the performance of the application.

Why do we need pagination?

For example, Let's take an e-commerce application, it has lots of products for sale to the customers. If we want to display the products on a website or mobile app then we have to show all the products page by page.

We can navigate the pages by clicking the page numbers. Each page displays only some products based on the record size that we want.

Pagination plays a vital role to increase the performance of the application. It gets only the pages with the list of records based on the page number and records size.

Types of pagination

There are two types of pagination we can display on the UI side. One is we can display all the pages on the UI side and navigate the pages through the page numbers. The other one is we can display the single page with data and navigate other pages through the next and previous buttons.

Page navigation through page numbers like below.

pagination-with-page-numbers

Page navigation through next and previous buttons like below.

pagination-with-next-and-previous-buttons

Now, let's start to see the implementation of pagination in the Spring Boot application with MongoDB configured.

Pagination using Page object in Spring Boot with MongoDB application

First, we have to create the spring boot application with MongoDB configured. We have already seen how to configure MongoDB with the Spring Boot application. If you want to know that please take a look at Spring Boot with MongoDB setup.

Now let us move to the pagination part directly. Below is the POJO class that is serialized with the MongoDB collection named 'user_profile'.

import org.bson.types.ObjectId;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection  = "user_profile")
public class ProfileVO {	
	
	@Id	
	private ObjectId _id;	
	private String firstName;	
	private String lastName;	
	private int age;
	
	public ObjectId get_id() {
		return _id;
	}
	public void set_id(ObjectId _id) {
		this._id = _id;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
	
}

Here we are going to do pagination with the MongoTemplate configuration of MongoDB in the Spring Boot application.

Generally, we can do pagination with the help of the Pageable in the spring boot application. Pageable is an interface that holds the PageRequest. In the PageRequest object, we can declare the page number and record size to get the page.

In the following ways, we can use the PageRequest options.

PageRequest.of(int page, int size) - This method passes the page number and records size to get the page.

PageRequest.of(int page, int size, Sort sort) - This method passes the page number, records size, and some sorting properties to get pages with sorted records.

PageRequest.of(int page, int size, Direction direction, String...properties) - This method passes the page number, records size, and direction properties to get the pages with ordered records.

Now let us see the examples of all the above.

public Page<ProfileVO> getAllProfiles(Integer page, Integer size) {

Pageable pageable = PageRequest.of(page, size);

Query query = new Query();
query.with(pageable);
	       
	        
return PageableExecutionUtils.getPage(
      mongoTemplate.find(query, ProfileVO.class),
      pageable,
      () -> mongoTemplate.count(query.skip(0).limit(0), ProfileVO.class)
);

}

If we pass 'page=0' and 'size=10' in the above method then it returns the first page with 10 records. page number always starts from 0 and the size we can mention whatever we want.

If we want to get the other pages then we have to increase the page number and pass it respectively like 1,2,3...etc.

mongoTemplate.find() gets the records from MongoDB based on the query and pageable object.

mongoTemplate.count() returns the total number of records based on the query.

Finally, the above method returns the page that has the content, pageable info, sorting info, total number of pages, and total number of records. The sample response looks like below.

{
    "content": [
        {
            "_id": {
                "timestamp": 1642919466,
                "date": "2022-01-23T06:31:06.000+00:00"
            },
            "firstName": "Akbar",
            "lastName": "Hasan",
            "age": 40
        },
        {
            "_id": {
                "timestamp": 1642919475,
                "date": "2022-01-23T06:31:15.000+00:00"
            },
            "firstName": "Allen",
            "lastName": "keller",
            "age": 40
        },
       ...
       ...
       ...
    ],
    "pageable": {
        "sort": {
            "unsorted": true,
            "sorted": false,
            "empty": true
        },
        "offset": 0,
        "pageNumber": 0,
        "pageSize": 10,
        "paged": true,
        "unpaged": false
    },
    "totalPages": 3,
    "totalElements": 23,
    "last": false,
    "size": 10,
    "number": 0,
    "sort": {
        "unsorted": true,
        "sorted": false,
        "empty": true
    },
    "numberOfElements": 10,
    "first": true,
    "empty": false
}

Pagination with Sorting properties

Below is an example of pagination with sorting.

public Page<ProfileVO> getAllProfiles(Integer page, Integer size) {

Pageable pageable = PageRequest.of(page, size, Sort.by("firstName").ascending());

Query query = new Query();
query.with(pageable);
	       
	        
return PageableExecutionUtils.getPage(
      mongoTemplate.find(query, ProfileVO.class),
      pageable,
      () -> mongoTemplate.count(query.skip(0).limit(0), ProfileVO.class)
);

}

If we pass 'page=0' and 'size=10' in the above method then it returns the first page with 10 records. It sorts the records by the ascending order of the first name. We can do sorting on a single field or multiple fields.

Pagination with Direction properties

Below is an example of pagination with Direction properties.

public Page<ProfileVO> getAllProfiles(Integer page, Integer size) {

Pageable pageable = PageRequest.of(page, size, Direction.DESC, "firstName");

Query query = new Query();
query.with(pageable);
	       
	        
return PageableExecutionUtils.getPage(
      mongoTemplate.find(query, ProfileVO.class),
      pageable,
      () -> mongoTemplate.count(query.skip(0).limit(0), ProfileVO.class)
);

}

If we pass 'page=0' and 'size=10' in the above method then it returns the first page with 10 records. It sorts the records by the descending order of the first name using Direction properties.

Pagination using Slice object in Spring Boot with MongoDB application

We can do pagination with the help of the Slice object in the spring boot application.

The main difference between using Slice and Page is Page holds some additional information like a total number of pages and a total number of elements but Slice doesn't have the info like that instead it has the info of availability of the next Slice.

If we use Slice for pagination then we can implement only the next and previous link pagination on the UI side. But we can't implement the pagination with page numbers. If you want to show all the pages and navigate the pages through page numbers then Page is the right choice.

Generally, Slice is the perfect choice if the navigation is based on the Next and Previous Page links. It improves the performance of the application when compared to Page.

The example is below.

public Slice<ProfileVO> getAllUserProfiles(Integer page, Integer size) {
		
Pageable pageable = PageRequest.of(page, size);	

Query query = new Query();
query.with(pageable);        
       
List<ProfileVO> profileList = mongoTemplate.find(query, ProfileVO.class);
       
        
return new SliceImpl<ProfileVO>(profileList,
	                pageable,true);

}

I hope you understood how to do pagination in the Spring Boot application with MongoDB configured by using Page and Slice. Thanks!. Keep Reading!.

Leave a Reply

Your email address will not be published. Required fields are marked *