Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to drop collection from database in MongoDB using Mongo DB JAVA driver?

Tags:

java

mongodb

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?

like image 548
rok Avatar asked Oct 21 '13 15:10

rok


People also ask

How do I drop multiple collections in MongoDB?

In MongoDB, you are allowed to delete the existing documents from the collection using db. collection. deleteMany() method. This method deletes multiple documents from the collection according to the filter.


2 Answers

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();
}
like image 87
Rondo Avatar answered Oct 22 '22 20:10

Rondo


I think this should work:

MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB("mydb");
DBCollection myCollection = db.getCollection("myCollection");
myCollection.drop();
like image 31
amazia Avatar answered Oct 22 '22 18:10

amazia