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?
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.
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();
}
I think this should work:
MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB("mydb");
DBCollection myCollection = db.getCollection("myCollection");
myCollection.drop();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With