MongoDB 3 Java check if collection exists

后端 未结 6 439
醉酒成梦
醉酒成梦 2020-12-06 05:13

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

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-06 05:31

    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;
    }
    

提交回复
热议问题