MongoDB - Java

MongoDB - PHP

MongoDB - Advanced

MongoDB - Useful Resources

MongoDB - Java - Dropping a Collection



MongoDB provides MongoCollection class to drop a collection.

Syntax

// Select a collection
MongoCollection<Document> collection =  database.getCollection("sampleCollection");
// drop the current collection
collection.drop();

Dropping the Collection

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

package com.tutorialspoint.mongodb;

import org.bson.Document;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

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.drop();       
         System.out.println("Collection dropped successfully.");
      }
   }
}

Output

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

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

Collection dropped successfully.
Advertisements