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
解决方案
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 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.