Java MongoDB Delete Multiple Documents

In this tutorial, you will learn how to delete multiple documents from a MongoDB collection using Java. The MongoDB Java Driver makes it easy to delete multiple documents that match a specified filter using the deleteMany() method.

What You Will Learn:

  • How to connect Java to MongoDB.
  • How to delete multiple documents from a MongoDB collection.
  • How to verify the deletion of multiple documents.

Technologies Used:

  • JDK: Version Java 21
  • MongoDB: Version 6.0 or later
  • MongoDB Java Driver: Version 5.1.4

Step 1: Add MongoDB Java Driver Dependency

You need to add the MongoDB Java Driver to connect your Java application to MongoDB.

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 are not using Maven or Gradle, download the MongoDB Java Driver JAR file and manually add it to your classpath.

Step 2: Write Java Code to Delete Multiple Documents

Below is the Java code that connects to MongoDB and deletes multiple documents from a collection.

Code Example:

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.DeleteResult;
import org.bson.Document;
import com.mongodb.client.model.Filters;

public class MongoDBDeleteMultipleDocumentsExample {

    // 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: Access the collection (it will create it if it doesn't exist)
            MongoCollection<Document> collection = database.getCollection("employees");

            // Step 4: Delete multiple documents where the department is "HR"
            DeleteResult result = collection.deleteMany(Filters.eq("department", "HR"));

            // Step 5: Check how many documents were deleted
            if (result.getDeletedCount() > 0) {
                System.out.println(result.getDeletedCount() + " documents deleted from the 'employees' collection.");
            } else {
                System.out.println("No documents found with the specified filter.");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Explanation with Code Snippets:

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

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

    The try-with-resources block ensures the MongoDB connection is closed automatically after the operation is complete.

  • Step 2: Access the Database Use getDatabase() to access the mydb database. MongoDB will create the database automatically if it doesn’t exist.

    MongoDatabase database = mongoClient.getDatabase("mydb");
    
  • Step 3: Access the Collection Use getCollection() to access the employees collection. MongoDB will create the collection automatically if it doesn’t exist.

    MongoCollection<Document> collection = database.getCollection("employees");
    
  • Step 4: Delete Multiple Documents The deleteMany() method is used to delete all documents that match the filter condition. In this case, we are deleting all documents where department = "HR".

    DeleteResult result = collection.deleteMany(Filters.eq("department", "HR"));
    
    • Filters.eq(): This is used to filter documents based on the condition you want. Here we are filtering documents where department is "HR".
  • Step 5: Check How Many Documents Were Deleted The DeleteResult.getDeletedCount() method returns the number of deleted documents. If it's greater than 0, it means documents were successfully deleted.

    if (result.getDeletedCount() > 0) {
        System.out.println(result.getDeletedCount() + " documents deleted from the 'employees' collection.");
    } else {
        System.out.println("No documents found with the specified filter.");
    }
    

Step 3: Run the Java Program

After writing the code, run the program in your IDE or from the command line. If multiple documents are deleted successfully, you will see an output like this:

3 documents deleted from the 'employees' collection.

If no documents were found with the specified filter, you will see:

No documents found with the specified filter.

Step 4: Verify the Deleted Documents

You can use the MongoDB shell or any MongoDB client tool to verify that the documents were deleted. In the MongoDB shell, use the following command:

use mydb
db.employees.find({ "department": "HR" })

If the documents were deleted successfully, no documents with department = "HR" will be returned.

Conclusion

In this tutorial, you learned how to:

  • Connect Java to MongoDB using the MongoDB Java Driver.
  • Delete multiple documents from a MongoDB collection using the deleteMany() method.
  • Verify the deletion of multiple documents using the MongoDB shell.

This approach is useful when you need to remove several documents from a MongoDB collection based on a filter. You can extend this method to handle more complex bulk deletions.

Comments