Java & MongoDB Tutorial
Java & MongoDB Useful Resources
Selected Reading
- Java & MongoDB - Sorting Records
- Java & MongoDB - Limiting Records
- Java & MongoDB - Referenced Documents
- Java & MongoDB - Embedded Documents
- Java & MongoDB - Delete Document
- Java & MongoDB - Update Document
- Java & MongoDB - Select Document
- Java & MongoDB - Insert Document
- Java & MongoDB - Display Collections
- Java & MongoDB - Drop Collection
- Java & MongoDB - Create Collection
- Java & MongoDB - Drop Database
- Java & MongoDB - Show Databases
- Java & MongoDB - Connect Database
- Java & MongoDB - Environment Setup
- Java & MongoDB - Overview
- Java & MongoDB - Home
Java & MongoDB Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Java & MongoDB - Delete Document
Java & MongoDB - Delete Document
To delete a document in a collection, you can use collection.deleteOne() method to delete a particular document of a collection.
collection.deleteOne(filter);
Example
Following is the code snippet to delete a document and display remaining documents −
import org.bson.Document; import com.mongodb.cpent.FindIterable; import com.mongodb.cpent.MongoCpent; import com.mongodb.cpent.MongoCpents; import com.mongodb.cpent.MongoCollection; import com.mongodb.cpent.MongoDatabase; import com.mongodb.cpent.model.Filters; pubpc class Tester { pubpc static void main(String[] args) { // Creating a Mongo cpent MongoCpent mongoCpent = MongoCpents.create("mongodb://localhost:27017"); MongoDatabase database = mongoCpent.getDatabase("myDb"); // Get the collection MongoCollection<Document> collection = database.getCollection("sampleCollection"); // Find all documents collection.deleteOne(Filters.eq("First_Name","Mahesh")); System.out.println("Document deleted."); System.out.println("***Documents***"); // Select a particular document FindIterable<Document> documents = collection.find(); for (Document document : documents) { System.out.println(document); } } }
Now, let s compile and run the above program as shown below.
$javac Tester.java $java Tester
Output
On executing, the above program gives you the following output.
Document deleted. ***Documents*** Document{{_id=60b70d426214461f10ac5c9a, First_Name=Radhika, Last_Name=Sharma, Date_Of_Birth=1995-09-26, e_mail=radhika_sharma.123@gmail.com, phone=9000012345}} Document{{_id=60b70d426214461f10ac5c9b, First_Name=Rachel, Last_Name=Christopher, Date_Of_Birth=1990-02-16, e_mail=Rachel_Christopher.123@gmail.com, phone=9000054321}} Document{{_id=60b70d426214461f10ac5c9c, First_Name=Fathima, Last_Name=Sheik, Date_Of_Birth=1990-02-16, e_mail=Fathima_Sheik.123@gmail.com, phone=9000054321}}Advertisements