首页 > 解决方案 > MongoDB - 帮助检测集合是否已经存在

问题描述

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.");
}

但是,如果我在没有现有集合的情况下第一次运行我的程序,它会创建一个名为“许可证”的集合;当我第二次运行它时,我的程序认为该集合不存在并尝试创建它,即使我可以在 MongoDB 指南针中清楚地看到它。我不知道为什么...

MongoDB 指南针:https ://prnt.sc/rd4ssa

标签: javadatabasemongodbcollectionsconnection

解决方案


看起来您正在使用过去的 API;您可以考虑使用较新的 MongoDB Java 驱动程序并使用其方法。例如:

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

推荐阅读