MongoDB Drop Collection Java Example - Java @ Desk

Wednesday, May 21, 2014

MongoDB Drop Collection Java Example

MongoDB Drop Collection Java Example

In our last post, we learned MongoDB Drop Collection example through command line.

This post explains how to drop or remove a complete collection in a Java Program.

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

dropIndexes() method removes all the indexes of the collection. This method is internally called from above method drop(). No need to explicitly call this.

Below example loads the collection "loans" and drops the collection


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 MongoDBDropCollection {

 public static void main(String args[]) throws UnknownHostException {
  DB database = getDatabase();

  DBCollection collection = database.getCollection("loans");


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

No comments:

Post a Comment