Java & MongoDB – Drop Database


Java & MongoDB – Drop Database



”;


To drop a databases, you can use MongoDatabse.drop() method to drop the selected databases.


// Creating a Mongo client 
MongoClient mongoClient = MongoClients.create();

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

// drop the database
database.drop();

Example

Following is the code snippet to drop a database −


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

public class Tester {
   public static void main(String[] args) {
      // Creating a Mongo client 
      MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
      MongoDatabase database = mongoClient.getDatabase("myDb");

      // drop the database
      database.drop();
      System.out.println("Database dropped.");
      
      // print the databases	   
      MongoIterable<String> list = mongoClient.listDatabaseNames();
      for (String name : list) {
         System.out.println(name);
      }
   }
}

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.


Database dropped.
admin
config
local

Advertisements

”;

Leave a Reply

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