I have the following problem:
I\'m using the Java driver for MongoDB 3.
In version 2 it was possible to do DB.collectionExists(name) to check whether a colle
I came across this post as I was trying to find out an efficient way to check if a collection exists. As I have more than 50k Collections in my database, using the listCollectionNames() method is extremely inefficient.
What I did was to use the db.collection.count() method and if it returned a non-zero value, then I would treat it as a non-existent collection. Ofcourse this is not hundred percent correct, since one could have a collection with zero entries and this approach would treat that as a non-existent collection. But for most scenarios in MongoDB, a collection makes sense only if it has at least one document. Following is a sample code,
public boolean isCollectionExists(DB db, String collectionName)
{
DBCollection table = db.getCollection(collectionName);
return (table.count()>0)?true:false;
}