MongoDB Drop All Collections From Database in Java - Java @ Desk

Wednesday, May 21, 2014

MongoDB Drop All Collections From Database in Java

MongoDB Drop All Collections From Database in Java

In our last post, we learned How to drop a collection from MongoDB in Java

drop() method is called on a DBCollection object to drop the entire collection along with the indexes associated.

In order to delete all the collections associated with the database, you need to make use of getCollectionNames() method of class com.mongodb.DB

Java Program:

import java.net.UnknownHostException;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;

public class MongoDBDropCollection {

 public static void main(String args[]) throws UnknownHostException {
  DB database = getDatabase();
  for (String string : database.getCollectionNames()) {
   DBCollection collection = database.getCollection(string);
   collection.drop();
  }
 }

 public static DB getDatabase() throws UnknownHostException {
  Mongo mongo = new Mongo("localhost", 27017);
  DB database = mongo.getDB("yourdb");
  return database;
 }
}






No comments:

Post a Comment