Delete data in MongoDB using Java

Here’s a sample code snippet that demonstrates how to delete data from a MongoDB database using Java and the MongoDB Java Driver:

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

public class MongoDBDataDeleter {
    public static void main(String[] args) {
        // MongoDB connection URI
        String uri = "mongodb://localhost:27017";

        // Database and collection names
        String databaseName = "mydatabase";
        String collectionName = "customers";

        try {
            // Connect to MongoDB
            MongoClientURI mongoURI = new MongoClientURI(uri);
            MongoClient mongoClient = new MongoClient(mongoURI);

            // Access the database
            MongoDatabase database = mongoClient.getDatabase(databaseName);

            // Access the collection
            MongoCollection<Document> collection = database.getCollection(collectionName);

            // Delete filter
            String fieldName = "name";
            String fieldValue = "John Doe";
            collection.deleteOne(Filters.eq(fieldName, fieldValue));

            System.out.println("Data deleted successfully!");

            // Close the MongoDB client
            mongoClient.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Make sure you have the MongoDB Java Driver (such as mongodb-driver.jar) included in your classpath. If not, you can download it from the official MongoDB website or include it as a Maven/Gradle dependency.

The code connects to the MongoDB database using the provided connection URI, accesses the specified database and collection, defines a filter to identify the document(s) to delete (in this case, based on the name field), and performs the deletion using the deleteOne() method.

Remember to handle exceptions appropriately in your production code and close the MongoDB client to release resources.

Pamai Tech
Turning ideas into Reality

Products

Office Add-in

Enterprise Solutions

Cloud Consulting

UI UX Design

Data Transformation

Services

FAQ's

Privacy Policy

Terms & Condition

Team

Contact Us

Company

About Us

Services

Features

Our Pricing

Latest News

© 2023 Pamai Tech