Java & MongoDB - Drop Database


Advertisements

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

Useful Video Courses


Video

Java Date and Time Online Training

16 Lectures 2 hours

Malhar Lathkar

Video

Java Servlet Online Training

19 Lectures 5 hours

Malhar Lathkar

Video

JavaScript Online Training

25 Lectures 2.5 hours

Anadi Sharma

Video

Java Online Training

Most Popular

126 Lectures 7 hours

Tushar Kale

Video

Java Essential Training

119 Lectures 17.5 hours

Monica Mittal

Video

Java Essentials Online Training

76 Lectures 7 hours

Arnab Chakraborty

Advertisements