Java MongoDB Driver 3.3.0 - Pagination Example

 Posted On  | Yashwant Chavan 

Pagination is most common requirement in any web application, It helps you to divide your result into number of discrete pages. Here I am using .skip() and .limit() modifiers to implement the pagination logic using java mongoDB driver.

Tools and Technologies

Basically we are using below tools and technologies

  1. Maven 3.0.4
  2. JDK 1.8
  3. Mongo Java Driver 3.3.0

Maven Dependencies

Define mongo-java-driver maven dependencies in pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.technicalkeeda</groupId>
    <artifactId>JavaExamples</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.3.0</version>
        </dependency>
    </dependencies>
</project>

Connecting to database

A MongoDB client internally uses the connection pooling mechanism. It has one MongoClient instance for the entire JVM. To connect the local mongoDb database use host name (localhost) and default port number (27017).

 MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));

Get the database instance

Once you are successfully connected, access the mongoDB database e.g.(technicalkeeda).

 MongoDatabase database = mongoClient.getDatabase("technicalkeeda");

Get Collection

Get persons collection from the database. It will create the new collection, if collection does not exist in the database.

 MongoCollection <Document> persons = database.getCollection("persons");

Pagination Full Example

Here I will walk you through an example which will display the collection data into number of pages using Java MongoDB. In this example, we have inserted number of records into persons collection and displaying respected records using pageNumber and pageSize.

package com.technicalkeeda.app;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;

public class App {
    public static void main(String[] args) {

        int pageSize = 3;
        int pageNumber = 1;

        MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));

        try {

            MongoDatabase database = mongoClient.getDatabase("technicalkeeda");
            MongoCollection <Document> persons = database.getCollection("persons");

            App app = new App();
            app.insert(persons);

            System.out.println("Insert Documents");

            System.out.println("Display 1st page number records");
            app.pagination(persons, pageNumber, pageSize);
            System.out.println();

            System.out.println("Display 2nd page number records");
            app.pagination(persons, pageNumber + 1, pageSize);
            System.out.println();

            System.out.println("Display 3rd page number records");
            app.pagination(persons, pageNumber + 2, pageSize);
            System.out.println();

            System.out.println("Display 4th page number records");
            app.pagination(persons, pageNumber + 3, pageSize);
            System.out.println();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            mongoClient.close();
        }
    }

    /* collection pagination */
    public void pagination(MongoCollection <Document> persons, int pageNumber, int pageSize) {

        try {

            MongoCursor <Document> cursor = persons.find().skip(pageSize * (pageNumber - 1)).limit(pageSize).iterator();

            while (cursor.hasNext()) {
                Document person = cursor.next();
                System.out.println(person);
            }
            cursor.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /* Insert records */
    public void insert(MongoCollection <Document> persons) {
        try {
            persons.insertOne(new Document().append("person_id", "1").append("name", "Yashwant").append("age", "32"));
            persons.insertOne(new Document().append("person_id", "2").append("name", "Nilesh").append("age", "30"));
            persons.insertOne(new Document().append("person_id", "3").append("name", "Dinesh").append("age", "25"));
            persons.insertOne(new Document().append("person_id", "4").append("name", "Kapil").append("age", "19"));
            persons.insertOne(new Document().append("person_id", "5").append("name", "Nitin").append("age", "40"));
            persons.insertOne(new Document().append("person_id", "6").append("name", "Ganesh").append("age", "23"));
            persons.insertOne(new Document().append("person_id", "7").append("name", "Vijay").append("age", "38"));
            persons.insertOne(new Document().append("person_id", "8").append("name", "Piyush").append("age", "30"));
            persons.insertOne(new Document().append("person_id", "9").append("name", "Hemant").append("age", "29"));
            persons.insertOne(new Document().append("person_id", "10").append("name", "Vinay").append("age", "26"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Program Output

Insert Documents

Display 1st page number records
Document{{_id=57ec9f228d616c10dce8eec0, person_id=1, name=Yashwant, age=32}}
Document{{_id=57ec9f228d616c10dce8eec1, person_id=2, name=Nilesh, age=30}}
Document{{_id=57ec9f228d616c10dce8eec2, person_id=3, name=Dinesh, age=25}}

Display 2nd page number records
Document{{_id=57ec9f228d616c10dce8eec3, person_id=4, name=Kapil, age=19}}
Document{{_id=57ec9f228d616c10dce8eec4, person_id=5, name=Nitin, age=40}}
Document{{_id=57ec9f228d616c10dce8eec5, person_id=6, name=Ganesh, age=23}}

Display 3rd page number records
Document{{_id=57ec9f228d616c10dce8eec6, person_id=7, name=Vijay, age=38}}
Document{{_id=57ec9f228d616c10dce8eec7, person_id=8, name=Piyush, age=30}}
Document{{_id=57ec9f228d616c10dce8eec8, person_id=9, name=Hemant, age=29}}

Display 4th page number records
Document{{_id=57ec9f228d616c10dce8eec9, person_id=10, name=Vinay, age=26}}

Shell Output

> use technicalkeeda
switched to db technicalkeeda
> db.persons.find().pretty()
{
        "_id" : ObjectId("57ec9f228d616c10dce8eec0"),
        "person_id" : "1",
        "name" : "Yashwant",
        "age" : "32"
}
{
        "_id" : ObjectId("57ec9f228d616c10dce8eec1"),
        "person_id" : "2",
        "name" : "Nilesh",
        "age" : "30"
}
{
        "_id" : ObjectId("57ec9f228d616c10dce8eec2"),
        "person_id" : "3",
        "name" : "Dinesh",
        "age" : "25"
}
{
        "_id" : ObjectId("57ec9f228d616c10dce8eec3"),
        "person_id" : "4",
        "name" : "Kapil",
        "age" : "19"
}
{
        "_id" : ObjectId("57ec9f228d616c10dce8eec4"),
        "person_id" : "5",
        "name" : "Nitin",
        "age" : "40"
}
{
        "_id" : ObjectId("57ec9f228d616c10dce8eec5"),
        "person_id" : "6",
        "name" : "Ganesh",
        "age" : "23"
}
{
        "_id" : ObjectId("57ec9f228d616c10dce8eec6"),
        "person_id" : "7",
        "name" : "Vijay",
        "age" : "38"
}
{
        "_id" : ObjectId("57ec9f228d616c10dce8eec7"),
        "person_id" : "8",
        "name" : "Piyush",
        "age" : "30"
}
{
        "_id" : ObjectId("57ec9f228d616c10dce8eec8"),
        "person_id" : "9",
        "name" : "Hemant",
        "age" : "29"
}
{
        "_id" : ObjectId("57ec9f228d616c10dce8eec9"),
        "person_id" : "10",
        "name" : "Vinay",
        "age" : "26"
}
>


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0356 seconds.