NoSQL Top

Build a Dashboard Using Cassandra, Astra, and Stargate:

>> CHECK OUT THE ARTICLE
Persistence top

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

>> CHECK OUT THE 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 = new MongoClient("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:

DB db = mongoClient.getDB("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 can be used to check whether a collection is present or not:

MongoClient mongoClient = new MongoClient("localhost", 27017);
DB db = mongoClient.getDB("baeldung");
String testCollectionName = "student";
System.out.println("Collection Name " + testCollectionName + " " + db.collectionExists(testCollectionName));

Here, the collectionExists method will return true if the collection exists, false otherwise.

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 {
    database.createCollection(testCollectionName);
} 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.count() > 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.

NoSql Bottom

Build a Dashboard Using Cassandra, Astra, and Stargate

>> CHECK OUT THE ARTICLE
Persistence bottom
Get started with Spring Data JPA through the reference Learn Spring Data JPA course: >> CHECK OUT THE COURSE
Persistence footer banner
Comments are closed on this article!