MongoDB - Java

MongoDB - PHP

MongoDB - Advanced

MongoDB - Useful Resources

MongoDB - Java - Delete Document



MongoDB provides MongoCollection class to delete a document of a collection.

Syntax

// Select a collection
MongoCollection<Document> collection =  database.getCollection("sampleCollection");
// delete document where title is MongoDB
collection.deleteOne(Filters.eq("title", "MongoDB"));

Deleting a Document in a Collection

To delete a document, we first need to connect to a database and then select the collection and then delete the document as shown below −

package com.tutorialspoint.mongodb;

import java.util.Iterator;

import org.bson.Document;

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;

public class MongoDBTester {

   public static void main(String args[]) {

      String uri = "mongodb://localhost:27017/";

      try (MongoClient mongoClient = MongoClients.create(uri)) {
         MongoDatabase database = mongoClient.getDatabase("myDb");

         // select a collection
         MongoCollection<Document> collection = database.getCollection("sampleCollection");

         collection.deleteOne(Filters.eq("title", "MongoDB"));       
         System.out.println("Document deleted successfully...");  

         // Getting the iterable object
         FindIterable<Document> iterDoc = collection.find();
         int i = 1;
         // Getting the iterator
         Iterator<Document> it = iterDoc.iterator();
         while (it.hasNext()) {
            System.out.println(it.next());
            i++;
         }
      }
   }
}

Output

Now, let's compile and run the above program to delete a document from a collection in our database myDb.

On executing, the above program gives you the following output.

Document deleted successfully...
Document{{_id=69675615b8a497382adfd88e, title=RethinkDB, description=database, likes=200, url=http://www.tutorialspoint.com/rethinkdb/, by=tutorials point}}
Advertisements