Java & MongoDB – Drop Collection


Java & MongoDB – Drop Collection



”;


To drop a databases, you can use collection.drop() method to drop a collection in the databases.


// Get the collection
MongoCollection<Document> collection = database.getCollection("sampleCollection");

// delete the collection
collection.drop();

Example

Following is the code snippet to drop a collection −


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 Tester {
   public static void main(String[] args) {
      // Creating a Mongo client 
      MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");

      // get the database
      MongoDatabase database = mongoClient.getDatabase("myDb");

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

      collection.drop();
      System.out.println("Collection dropped.");
   }
}

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.


Collection dropped.

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *