簡體   English   中英

MongoDB - 幫助檢測集合是否已經存在

[英]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.");
}

但是,如果我在沒有現有集合的情況下第一次運行我的程序,它會創建一個名為“許可證”的集合; 當我第二次運行它時,我的程序認為該集合不存在並嘗試創建它,即使我可以在 MongoDB 指南針中清楚地看到它。 我不知道為什么...

MongoDB 指南針: https : //prnt.sc/rd4ssa

看起來您正在使用過去的 API; 您可以考慮使用較新的 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.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM