MongoDB Drop Database Java Example | Java @ Desk
Home » » MongoDB Drop Database Java Example

MongoDB Drop Database Java Example

MongoDB Drop Database Java Example

Drop a database removes all the collections and indexes associated plus all data files. It simply cleans up the complete database.

This command obtains a global write lock and will block other operations until it has completed.

To drop a single database :
1) Load the DB object for the database
2) Call the dropDatabase() method

To drop all the database in MongoDB in java :
1) Iterate through the list of database names
2) Load the DB object for the database
3) Call the dropDatabase() method

Java Program :

import java.net.UnknownHostException;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.WriteResult;

public class MongoDBDropDatabase {

 public static void main(String args[]) throws UnknownHostException {
  Mongo mongo = new Mongo("localhost", 27017);
  
  // Drop a Single Database
  DB database = mongo.getDB("yourdb");
  database.dropDatabase();

  // Drop all the database
  for (String string : mongo.getDatabaseNames()) {
   DB db = mongo.getDB(string);
   db.dropDatabase();
  }
 }
}




0 comments:

Post a Comment