English 中文(简体)
Java & MongoDB - Drop Collection
  • 时间:2024-09-17

Java & MongoDB - Drop Collection


Previous Page Next Page  

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.cpent.MongoCpent;
import com.mongodb.cpent.MongoCpents;
import com.mongodb.cpent.MongoCollection;
import com.mongodb.cpent.MongoDatabase;

pubpc class Tester {
   pubpc static void main(String[] args) {
      // Creating a Mongo cpent 
      MongoCpent mongoCpent = MongoCpents.create("mongodb://localhost:27017");

      // get the database
      MongoDatabase database = mongoCpent.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