Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:


1. Overview

MongoDB is a NoSQL database that stores the data records as BSON documents into a collection. We can have multiple databases, and each database can have one or more collections of documents.

Unlike relational databases, MongoDB creates the collection with the inserted document without the need for any structure definition. In this tutorial, we’ll learn various ways to check the existence of a collection. We’ll use the collectionExists, createCollection, listCollectionNames, and count method to check the collection’s existence.

2. Database Connectivity

In order to access any data of a collection, we first need to set up a connection with the database. Let’s connect to the MongoDB database that is running locally on our machine.

2.1. Create Connection Using the MongoClient

MongoClient is a Java class used to establish a connection with the MongoDB instance:

MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");

Here, we are connecting to MongoDB that is running at port default port 27017 on localhost.

2.2. Connect to Database

Now, let’s use the MongoClient object to access the database. There are two methods to access the database using the MongoClient.

First, we’ll use the getDatabase method to access the baeldung database:

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

We can also use the getDB method of Mongo Java driver to connect to the database:

MongoDatabase db = mongoClient.getDatabase("baeldung");

The getDB method is deprecated, hence it is not recommended to use.

So far, we have set up a connection with MongoDB using the MongoClient and further connected to the baeldung database.

Let’s deep dive into different approaches to check the existence of a collection in MongoDB.

3. Using the DB Class

The MongoDB Java Driver provides both synchronous and asynchronous method calls. In order to connect to the database, we just need to specify the database name. If the database is not present, MongoDB will automatically create one.

The collectionExists method does not exists in the newer version a work around was created based on the listCollectionNames() to check whether a collection is present or not:

MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
MongoDatabase db = mongoClient.getDatabase("baeldung");
String testCollectionName = "student";
System.out.println("Collection Name " + testCollectionName + " " + db.listCollectionNames().into(new ArrayList<>()).contains(testCollectionName));

Here, the listCollectioNames method will return all the collections and then match with the desired collection.

The com.mongodb.DB API of the MongoDB Java driver is deprecated from version 3.x, but it is still accessible. Hence, the DB class is not recommended to use for a new project.

4. Using the MongoDatabase Class

The com.mongodb.client.MongoDatabase is an updated API for Mongo 3.x and above. Unlike the DB class, the MongoDatabase class does not provide any specific method to check the existence of a collection. But, there are various methods that we can use to get the desired results.

4.1. Using the createCollection Method

The createCollection method creates a new collection in MongoDB. But we can also use it to check whether a collection exists or not:

String databaseName="baeldung";
MongoDatabase database = mongoClient.getDatabase(databaseName);
String testCollectionName = "student";
try {
} catch (Exception exception) {
    System.err.println("Collection:- "+testCollectionName +" already Exists");

The above code will create a new collection “student” if it isn’t already present in the database. The createCollection method will throw an exception in case the collection already exists.

This approach isn’t recommended as it creates a new collection in the database.

4.2. Using the listCollectionNames Method

The listCollectionNames method lists all the collections names in the database. Hence, we can use this method to solve the issue of collection existence.

Lets now look into an example code of listCollectionNames method using the Java driver code:

String databaseName="baeldung";
MongoDatabase database = mongoClient.getDatabase(databaseName);
String testCollectionName = "student";
boolean collectionExists = database.listCollectionNames()
  .into(new ArrayList()).contains(testCollectionName);
System.out.println("collectionExists:- " + collectionExists);

Here, we have iterated over the list of all the collection names in the database baeldung. For each occurrence, we match the collection string name with the testCollectionName. It will return true on a successful match, false otherwise.

4.3. Using the count Method

The count method of the MongoCollection counts the number of documents present in a collection.

As a workaround, we can use this method to check for the collection’s existence. Here is the Java code snippet for the same:

String databaseName="baeldung";
MongoDatabase database = mongoClient.getDatabase(databaseName);
String testCollectionName = "student";
MongoCollection<Document> collection = database.getCollection(testCollectionName);
Boolean collectionExists = collection.countDocuments() > 0 ? true : false;
System.out.println("collectionExists:- " + collectionExists);
Boolean expectedStatus = false;
assertEquals(expectedStatus, collectionExists);

This method doesn’t work if a collection exists without any data, In that case, it will return 0, but the collection exists with empty data.

5. Conclusion

In this article, we’ve explored various ways to check the existence of a collection using the MongoDatabase and DB class methods.

In short, the collectionExists method of com.mongodb.DB class and listCollectionNames method of com.mongodb.client.MongoDatabase are recommended to check the collection’s existence.

As always, the source code and code snippet of all the examples is available over on GitHub.

Course – LSD (cat=Persistence)

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:

res – Persistence (eBook) (cat=Persistence)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.