java - 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.
}
推荐阅读
- c - 线程处理
- javascript - 遍历文件夹并导入 index.js
- python - Keras 中的发散损失与自定义损失
- java - 如何处理 RestControllerAdvice 中抛出的异常?
- javascript - 在哪里放置`axios.interceptor`?在 react-create-app 的单独服务中?
- laravel - 从关系表中提取数据到 AppServiceProvider
- scala - 没有退货声明如何提前退货?
- php - 如何发布woocommerce结帐字段html值
- javascript - PHP 邮件显示没有链接的文本
- javascript - 错误:“NgxSmartModalService”类型上不存在属性“modalStack”。您的意思是“_modalStack”吗?