gpt4 book ai didi

java - MongoDB - 帮助检测集合是否已经存在

转载 作者:太空宇宙 更新时间:2023-11-04 09:02:44 24 4
gpt4 key购买 nike

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;您可以考虑使用newer MongoDB Java Driver并使用其方法。例如:

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

关于java - MongoDB - 帮助检测集合是否已经存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60582481/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com