MongoDB - help detecting whether a collection already exists or not

Viewed 2384
DB database = mongo.getDB("pluginlicenser");
if(!database.collectionExists("licenses")){
    System.out.println("Collections: " + database.getCollectionNames());
    System.out.println("Creating new license collection...\nstarting up...");
    database.createCollection("licenses", new BasicDBObject());
}else{
    System.out.println("licenses collection already exists...\nloading details.");
}

If I run my program for the first time with no existing collection, it creates the collection called "licenses", however; when I run it a second time my program thinks that the collection doesn't exist and tries to create it even though I can clearly see it in the MongoDB compass. I don't know why...

MongoDB Compass: https://prnt.sc/rd4ssa

1 Answers

It looks like you are using APIs from the past; you can consider using the newer MongoDB Java Driver and use its methods. For example:

MongoClient mongoClient = MongoClients.create("mongodb://localhost/");
MongoDatabase database = mongoClient.getDatabase("test");
List<String> collectionNames = database.listCollectionNames()
                                        .into(new ArrayList<>());

if (collectionNames.contains("newColl")) {    
    System.out.println("Collection exits...");
}
else {
    System.out.println("Collection doesn't exit, creating new...");
    // code to create collection, etc.
}
Related