Delete a Document in MongoDB using Java
In this example, We will show you sample program about, How to Delete a Document in MongoDB using Java. The example were tested and shared in the same post.
Insert Documents
/* 1 */ { "_id" : 101, "name" : "John", "designation" : "Software Engineer" } /* 2 */ { "_id" : 102, "name" : "Dinesh", "designation" : "Sr. Software Engineer" } /* 3 */ { "_id" : 103, "name" : "Smith", "designation" : "Project Manager" } /* 4 */ { "_id" : 104, "name" : "William", "designation" : "Software Engineer" } /* 5 */ { "_id" : 105, "name" : "James", "designation" : "Business Analyst" }
Example Program
package com.dineshkrish.mongo; import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; /** * * @author Dinesh Krishnan * */ public class DeleteDocument { public static void main(String[] args) { // host name final String HOST_NAME = "localhost"; // default port number final int PORT = 27017; // creating mongo client object MongoClient client = new MongoClient(HOST_NAME, PORT); // selecting the mongo database MongoDatabase database = client.getDatabase("dineshkrish"); // selecting the mongo collection MongoCollection<Document> collection = database .getCollection("employee_records"); // preparing delete query Document query = new Document(); query.put("_id", 101); // deleting the document collection.deleteOne(query); System.out.println("Document Deleted Successfully..."); // closing the client client.close(); } }
Output
Before Deleting the Document
After Deleting the Document
References
1. MongoDB Java API Documentation
2. JavaDoc – MongoClient Class
3. JavaDoc – MongoDatabase Interface
4. JavaDoc – Document Class
More from my site

Hello, folks, I am a founder of idineshkrishnan.com. I love open source technologies, If you find my tutorials are useful, please consider making donations to these charities.
No responses yet