【问题标题】:MongoDB - help detecting whether a collection already exists or notMongoDB - 帮助检测集合是否已经存在
【发布时间】:2020-03-07 21:44:42
【问题描述】:
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

【问题讨论】:

  • 您可以将过滤器参数传递给 listCollections,例如 db.runCommand("listCollections", {filter: {name: "CollectionName"}}) - 如果集合不存在则返回 null

标签: java database mongodb collections connection


【解决方案1】:

您似乎在使用过去的 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.
}

【讨论】:

    猜你喜欢
    • 2019-08-04
    • 2023-03-13
    • 2015-11-01
    • 2018-02-27
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多