[英]MongoDB - help detecting whether a collection already exists or not
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.
当我第二次运行它时,我的程序认为该集合不存在并尝试创建它,即使我可以在 MongoDB 指南针中清楚地看到它。 I don't know why...
我不知道为什么...
MongoDB Compass: https://prnt.sc/rd4ssa MongoDB 指南针: https : //prnt.sc/rd4ssa
It looks like you are using APIs from the past;看起来您正在使用过去的 API; you can consider using the newer MongoDB Java Driver and use its methods.
您可以考虑使用较新的 MongoDB Java Driver并使用其方法。 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.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.