How to Count the Number of Documents Returned in Query Using Java

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

  • Being able to query the number of documents in a collection can be very useful for a variety of functions, such as when trying to determine how often a certain type of data occurs. There are various ways of counting the number of returned documents in a query. This tutorial will provide two specific examples on how to count the number of documents returned in query using Java with MongoDB, the MongoDB Java driver and Eclipse IDE.

Prerequisites

  • You must have MongoDB and the MongoDB Java driver properly installed and configured. NOTE: For this tutorial, MongoDB version 4.0 and MongoDB Java Driver 3.8.2. are used.
  • You must have the latest Java JDK properly installed and configured.
  • It will help to have an understanding of Eclipse IDE, as it is used in this tutorial.

Starting the MongoDB Database Daemon

  • First, open your terminal by pressing the Ctrl + Alt + T keys.
  • Next, start the MongoDB service and check the status using the below command.
  • You can use the sudo command to avoid permission-related issue while starting the MongoDB service.
1
2
sudo systemctl start mongod
sudo systemctl status mongod
  • The information return should resemble the following:
1
2
3
4
5
6
7
8
9
10
‚óè 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
Docs: https://docs.mongodb.org/manual
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)

How to Count the Number of Returned MongoDB Documents in a Query

  • Below are two specific examples of ways on how to count the number of documents returned in query using Java.

Example 1

1
2
3
4
5
6
7
8
9
10
11
public class MongoClass {

public static void main(String[] args) {

MongoClient mongo = MongoClients.create("mongodb://127.0.0.1:27017"); // (1)
MongoDatabase db = mongo.getDatabase("playerDB"); // (2)
MongoCollection<document> collection = db.getCollection("palyer_info"); // (3)
System.out.println(collection.countDocuments()); // (4)
}

}
  1. Instantiate the MongoClient object by specifically stating the hostname and port number.
  2. This will select the database “playerDB” using the getDatabase() method.

NOTE: If no database exists, MongoDB will create the database when data is entered into the specified database.

  1. This will select the collection “player_info” using the getCollection method from the MongoDatabase instance.

NOTE: If no database exists, MongoDB will create the collection when data is entered into the specified collection.

  1. This will print the number of documents within the collection using the countDocuments() method.

Example 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public int getDocCount2() {

MongoClient mongo = MongoClients.create("mongodb://127.0.0.1:27017"); // (1)
MongoDatabase db = mongo.getDatabase("playerDB"); // (2)
MongoCollection<document> collection = db.getCollection("palyer_info"); // (3)

FindIterable<document> docsIterable = collection.find(); // (4)
try (MongoCursor<document> iterator = docsIterable.iterator()){
int count = 0;
while (iterator.hasNext()) {
iterator.next();
count++;
}
System.out.println(count);
}
}
  1. Instantiate the MongoClient object by specifically stating the hostname and port number.

  2. This will select the database “playerDB” using the getDatabase() method.

NOTE: If a database does not exist, MongoDB will create the database when data is entered into the specified database.

  1. This will select the collection “player_info” using the getCollection method from the MongoDatabase instance.

NOTE: If a collection do not exist, MongoDB will create the collection when data is entered into the specified collection.

  1. This will result in the program looping through the collection and comparing the count variable to the number of found documents.

Conclusion

This article demonstrated two basic examples of how to count the number of documents returned in query using Java from a MongoDB query. Remember, you must have MongoDB and the MongoDB Java driver as well as the latest Java Development Kit properly installed and configured on your machine in order to count the number of documents returned in query using Java. Also note, if a database or collection does not exist, MongoDB will create the database or collection when you enter data into the specified database.

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.