Java MongoDB Drop Collection Example

In this tutorial, we will walk through how to drop a collection from a MongoDB database using Java. Dropping a collection removes it along with all of its data. We will use the MongoDB Java Driver to connect to MongoDB, drop a collection, and verify its deletion.

What You Will Learn:

  • How to connect to MongoDB using Java.
  • How to drop a collection from a MongoDB database.
  • How to confirm the deletion of a collection.

Technologies Used:

  • JDK: Version 1.8 or later (Recommended: Latest version)
  • MongoDB: Version 6.0 or later
  • MongoDB Java Driver: Version 5.1.4 (latest)

Step 1: Add MongoDB Java Driver Dependency

You need to include the MongoDB Java Driver in your project.

For Maven Users:

Add the following dependency to your pom.xml file:

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver-sync</artifactId>
    <version>5.1.4</version>
</dependency>

For Gradle Users:

Add the following line to your build.gradle file:

implementation 'org.mongodb:mongodb-driver-sync:5.1.4'

If you’re not using Maven or Gradle, you can download the JAR file from the MongoDB website and manually add it to your classpath.

Step 2: Write Java Code to Drop a MongoDB Collection

Here’s the Java program to connect to MongoDB and drop a collection.

Code Example:

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;

public class MongoDBDropCollectionExample {

    // MongoDB connection URI
    private static final String URI = "mongodb://localhost:27017";

    public static void main(String[] args) {
        // Step 1: Create a MongoClient instance to connect to MongoDB
        try (MongoClient mongoClient = MongoClients.create(URI)) {
            
            // Step 2: Access the database (it will create it if it doesn't exist)
            MongoDatabase database = mongoClient.getDatabase("mydb");

            // Step 3: Drop the collection
            database.getCollection("employees").drop();

            // Step 4: Confirm collection drop
            System.out.println("Collection 'employees' dropped successfully from database: " + database.getName());
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Explanation with Code Snippets:

  • Step 1: Create a MongoClient Instance The MongoClient is used to establish a connection to the MongoDB server. The connection string mongodb://localhost:27017 is used to connect to MongoDB running locally.

    try (MongoClient mongoClient = MongoClients.create(URI)) {
    

    We use a try-with-resources block to ensure the MongoClient is closed automatically after use.

  • Step 2: Access the Database The getDatabase() method connects to the mydb database. If the mydb database doesn't exist, MongoDB will create it when needed.

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

    This returns a MongoDatabase object, which allows interaction with the mydb database.

  • Step 3: Drop the Collection The drop() method is called on the collection you want to remove. Here, we drop the employees collection from the mydb database.

    database.getCollection("employees").drop();
    

    This will remove the collection and all of its documents from the database.

  • Step 4: Confirm Collection Drop After dropping the collection, we print a message to the console confirming that the collection has been successfully dropped.

    System.out.println("Collection 'employees' dropped successfully from database: " + database.getName());
    

Step 3: Run the Java Program

After writing the code, run the program in your IDE or from the command line. If everything is correct, you should see the following output:

Collection 'employees' dropped successfully from database: mydb

If there is an issue, such as MongoDB not running or the collection not existing, an error message will be printed.

Step 4: Verify Collection Deletion

To confirm that the collection has been dropped, use the MongoDB shell or a MongoDB client tool. In the MongoDB shell, you can list all collections in the mydb database with the following commands:

use mydb
show collections

The employees collection should no longer appear in the list.

Conclusion

In this tutorial, you learned how to:

  • Connect to MongoDB using Java.
  • Drop a collection using the MongoDB Java Driver.
  • Verify the deletion of a collection.

Dropping collections is a straightforward operation but should be used with caution, as it permanently deletes all data within the collection. Make sure to back up your data if needed before performing such operations.

Comments