MongoDB Get Document Count using Java

In this example, We will show you sample program about, How to perform MongoDB get document count using Java. The same program has been shared in the post with output.

Example Program

package com.dineshkrish.mongo;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
* @author Dinesh Krishnan
public class DeleteDocument {
public static void main(String[] args) {
// host name
final String HOST_NAME = "localhost";
// default port number
final int PORT = 27017;
// creating mongo client object
MongoClient client = new MongoClient(HOST_NAME, PORT);
// selecting the mongo database
MongoDatabase database = client.getDatabase("dineshkrish");
// selecting the mongo collection
MongoCollection<Document> collection = database
// getting the document count
System.out.println("Total Document Count is : "+collection.count());
// closing the client


Total Document Count is : 5


1. MongoDB Java API Documentation
2. JavaDoc – MongoClient Class
3. JavaDoc – MongoDatabase Interface
4. JavaDoc – Document Class

No responses yet

Leave a Reply

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