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

看起来您使用的是过去的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.
}

相关内容

最新更新