Java MongoDB Delete Document Example

In this tutorial, you will learn how to delete a document from a MongoDB collection using Java. Deleting a document from MongoDB can be easily done using the MongoDB Java Driver by applying filters to identify the specific document.

What You Will Learn:

  • How to connect Java to MongoDB.
  • How to delete a document from a MongoDB collection.
  • How to verify the document deletion.

Technologies Used:

  • JDK: Version 21 (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 don't use Maven or Gradle, you can download the MongoDB Java Driver JAR file and manually add it to your classpath.

Step 2: Write Java Code to Delete a Document

Here’s a Java program that connects to MongoDB and deletes a document 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 MongoDBDeleteDocumentExample {

    // 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 a document where "name" is "Raj"
            DeleteResult result = collection.deleteOne(Filters.eq("name", "Raj"));

            // Step 5: Check if the document was deleted
            if (result.getDeletedCount() > 0) {
                System.out.println("Document deleted from the 'employees' collection.");
            } else {
                System.out.println("No document 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 the MongoDB server using the connection string mongodb://localhost:27017.

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

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

  • 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 a Document The deleteOne() method is used to delete a single document that matches the filter. Here, we are deleting the document where name = "Raj".

    DeleteResult result = collection.deleteOne(Filters.eq("name", "Raj"));
    
    • Filters.eq(): This is used to specify the filter condition to find the document you want to delete.
  • Step 5: Check If the Document Was Deleted The DeleteResult.getDeletedCount() method returns the number of deleted documents. If it's greater than 0, it means the document was successfully deleted.

    if (result.getDeletedCount() > 0) {
        System.out.println("Document deleted from the 'employees' collection.");
    } else {
        System.out.println("No document 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 the document is deleted successfully, you will see the following output:

Document deleted from the 'employees' collection.

If the document was not found, the following message will be printed:

No document found with the specified filter.

Step 4: Verify the Deleted Document

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

use mydb
db.employees.find({ "name": "Raj" })

If the document was deleted successfully, no document with name = "Raj" will be returned.

Conclusion

In this tutorial, you learned how to:

  • Connect Java to MongoDB using the MongoDB Java Driver.
  • Delete a document from a MongoDB collection using the deleteOne() method.
  • Verify that the document was deleted using the MongoDB shell.

This approach allows you to remove specific documents from a MongoDB collection based on filter conditions. You can extend this method to handle bulk deletions using the deleteMany() method.

Comments