12

The following commands were typed using mongo.exe client (assuming that the collection coll exists) :

> use database
switched to db database
>db.coll.drop()
True

How to perform db.coll.drop() using Mongo DB JAVA driver?

2 Answers 2

22

I think this should work:

MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB("mydb");
DBCollection myCollection = db.getCollection("myCollection");
myCollection.drop();
Sign up to request clarification or add additional context in comments.

Comments

12

The current accepted answer would create a collection that did not previously exist and delete it, since getCollection creates one by the given name if it does not exist. It would be more efficient to check for existence first:

MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB("mydb");
if (db.collectionExists("myCollection")) {
    DBCollection myCollection = db.getCollection("myCollection");
    myCollection.drop();
}

2 Comments

What version of the driver are you using? I am using 3.3.0 and couldn't find the collectionExists method.
I don't know what I was using back then.... that method still exists in 3.3 and 3.4... here are the 3.4 api docs: api.mongodb.com/java/3.3/com/mongodb/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.