How to Limit the Query results in MongoDB using in Eclipse using Java


If you’re a Java developer working with MongoDB, it’s important to know how to create different queries in order to get the results you need. Normally, a MongoDB query performed using Java will return all matching results; however, there may be times when you need to limit your results to a specific number. Fortunately, it’s easy to accomplish this task with some simple code. In this article, we’ll show an example of limiting MongoDB query results in Eclipse using Java.


Before we can dive into the Java code, we’ll need to review the system requirements for this task. In this case, there are only a few prerequisites:

  • Make sure that MongoDB as well as the MongoDB Java driver are installed and properly configured beforehand.

  • Make sure that the latest Java JDK is properly installed and configured beforehand.

  • In this article, Eclipse IDE will be used. It’s helpful to use the same IDE in order to follow along with the tutorial.

Starting the MongoDB Database Daemon

Once all the prerequisites have been confirmed, we can proceed to the next step– starting up the MongoDB service. If you don’t have a terminal window open, press Ctrl + Alt + T to open one up. Then, you can start the MongoDB service and check its status using the following command. It’s a good idea to use sudo with this command to avoid running into any permission-related issues when you start up the service.

sudo systemctl start mongod
sudo systemctl status mongod

After running the command, you should see something like this:

â— mongod.service - MongoDB Database Server
Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset:
Active: active (running) since Mon 2019-04-22 19:27:02 PST; 8min ago
Main PID: 6598 (mongod)
CGroup: /system.slice/mongod.service
└─6598 /usr/bin/mongod --config /etc/mongod.conf

Apr 22 19:27:02 teamsolo systemd[1]: Started MongoDB Database Server.
lines 1-9/9 (END)

NOTE: In this article, we assume that the MongoDB version used is 4.0 and MongoDB Java Driver is 3.8.2.

The Dataset

In order to show some example queries, we’ll need a dataset to work with. Below, you’ll see the sample dataset that will be used throughout this article:

"_id" : ObjectId("5cd56e315623d0556fb0b45e"),
"playerName" : "Ronaldo",
"age" : 25,
"nationality" : "Filipino",
"JerseyNumber" : 23,
"position" : "Guard"
"_id" : ObjectId("5cd64bc45623d00955cb3cbf"),
"playerName" : "Steve",
"age" : 25,
"nationality" : "Filipino",
"JerseyNumber" : 15,
"position" : "Point Guard"
"_id" : ObjectId("5cd64c5b5623d009c1fff26d"),
"playerName" : "yeshua",
"age" : 25,
"nationality" : "Filipino",
"JerseyNumber" : 21,
"position" : "Center"
"_id" : ObjectId("5cd671a05623d014e610973c"),
"playerName" : "Andre",
"age" : 25,
"nationality" : "Filipino",
"JerseyNumber" : 3,
"position" : "Center"
"_id" : ObjectId("5cd671ca5623d0150e44c7c2"),
"playerName" : "Jomar",
"age" : 25,
"nationality" : "Mexican",
"JerseyNumber" : 33,
"position" : "Forward"

Connecting to the MongoClient

At this point, we’re ready to look at some Java code. To connect a MongoClient instance to a MongoDB deployment, use the command shown below:

MongoClient mongo = MongoClients.create("mongodb://");

Accessing the Database

Now that the MongoClient instance is connected to a MongoDB deployment, we can use the following command to access the "PlayerDB" database:

MongoDatabase db = mongo.getDatabase("PlayerDB");

You can see that the getDatabase() method accepts the name of the database to connect to.

Get the MongoDB Collection

The line of code shown below will access a specific collection:

MongoCollection<document> collection = db.getCollection("playerInfo");

Note that the getCollection() method accepts the name of the collection.

Limiting the Query Results

There are times when you only want a query to return a certain number of results. The code shown below allows you to limit your query results:

FindIterable<document> findIterable =
MongoCursor<document> iterator = findIterable.iterator();
int count = 0;
while (iterator.hasNext()) {;

findIterable.forEach((Block<document>) System.out::println);

Unless you specify otherwise, the .find() method will retrieve all the documents within a collection. By using the .limit() method, you can limit the number of documents that are returned by specifying a number: .limit(4).

The results should look something like this:

Document{{_id=5cd56e315623d0556fb0b45e, playerName=Ronaldo, age=25, nationality=Filipino, JerseyNumber=23, position=Guard}}
Document{{_id=5cd64bc45623d00955cb3cbf, playerName=Steve, age=25, nationality=Filipino, JerseyNumber=15, position=Point Guard}}
Document{{_id=5cd64c5b5623d009c1fff26d, playerName=yeshua, age=25, nationality=Filipino, JerseyNumber=21, position=Center}}
Document{{_id=5cd671a05623d014e610973c, playerName=Andre, age=25, nationality=Filipino, JerseyNumber=3, position=Center}}

NOTE: While we used a limit of 4 in our example, the limit value can be changed to specify the maximum number of documents to be returned.


If you need to query MongoDB from Java, the find() method makes it easy to get the results you need. However, you may not always want your query to return all matching results. Our example shows how easy it is to specify the maximum number of results you’d like to return from a given query. With the step-by-step instructions provided in this article, you’ll have no trouble limiting MongoDB query results in Eclipse using Java.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.