MongoDB 3 Java check if collection exists

拈花ヽ惹草 提交于 2019-11-27 03:12:15

问题


I have the following problem:

I'm using the Java driver for MongoDB 3.

In version 2 it was possible to do DB.collectionExists(name) to check whether a collection exists in the selected database.

In version 3 with the switch from DB to MongoDatabase this method no longer exists.

How do I find out whether a collection exists inside a database? I tried to iterate over the collections with listCollectionNames() but this seems quite ineffective.

Thanks for your help


回答1:


You are correct. It appears as if the 3.0.x version of MongoDB driver did not port over a direct "does collection exist?" method to MongoDatabase.

As you already mentioned, one option for you is to iterate through the results of listCollectionNames(). While this seems ineffective, it is very similar to what the implementation of the DB.collectionExists(String) method does. The code snippet below was copied from the DB.java class in mongo-java-driver source:

public boolean collectionExists(final String collectionName) {
    Set<String> collectionNames = getCollectionNames();
    for (final String name : collectionNames) {
        if (name.equalsIgnoreCase(collectionName)) {
            return true;
        }
    }
    return false;
}

You could also get DB instead of MongoDatabase from the MongoClient by calling the getDB method. That gives you access to the collectionExists method which is deprecated. Of course, I do not recommend this second approach because, as mentioned, it is deprecated.

As a result, go with your iteration over listCollectionNames approach.




回答2:


One alternative is to use the MongoIterable.into function to add these to a target ArrayList that you can call contains("collectionName") on.

boolean collectionExists = client.getDatabase("dbName").listCollectionNames()
    .into(new ArrayList<String>()).contains("collectionName")



回答3:


for anyone still looking: Assuming you have MongoDatabase instance called "db"

try {
        db.createCollection("myCol");
    } catch (MongoCommandException e) {
        System.err.println("Collection Exists");
    }



回答4:


I came across this post as I was trying to find out an efficient way to check if a collection exists. As I have more than 50k Collections in my database, using the listCollectionNames() method is extremely inefficient.

What I did was to use the db.collection.count() method and if it returned a non-zero value, then I would treat it as a non-existent collection. Ofcourse this is not hundred percent correct, since one could have a collection with zero entries and this approach would treat that as a non-existent collection. But for most scenarios in MongoDB, a collection makes sense only if it has at least one document. Following is a sample code,

public boolean isCollectionExists(DB db, String collectionName) 
{

    DBCollection table = db.getCollection(collectionName);
    return (table.count()>0)?true:false;
}



回答5:


MongoIterable <String> collection =  database.listCollectionNames();
    for(String s : collection) {
        if(s.equals("collectionName")) {
            return true;

        }
    }
    return false;
}



回答6:


I found this post while searching for the exact same question. Using the newest driver, i.e.:

<!-- Mongo driver, GeoJson with Jackson, Gson for Mongo (Jongo) -->
<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.3.0</version>
</dependency>

someone may want to use:

public boolean collectionExists(final String db, final String collectionName) {
    final MongoDatabase database = client.getDatabase(db);
    if (database == null) {
            return false;
    }

    final MongoIterable<String> iterable = database.listCollectionNames();
    try (final MongoCursor<String> it = iterable.iterator()) {
        while (it.hasNext()) {
            if (it.next().equalsIgnoreCase(collectionName)) {
                return true;
            }
        }
    }

    return false;
}


来源:https://stackoverflow.com/questions/31909247/mongodb-3-java-check-if-collection-exists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!