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
The collectionExists method can be used to check whether a collection is present or not: MongoClient mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient. getDB("baeldung"); String testCollectionName = "student"; System. out.
If a collection does not exist, MongoDB creates the collection when you first store data for that collection. You can also explicitly create a collection with various options, such as setting the maximum size or the documentation validation rules.
To obtain a list of MongoDB collections, we need to use the Mongo shell command show collections . This command will return all collections created within a MongoDB database. To be able to use the command, we'll first need to select a database where at least one collection is stored.
Delete Collection You can delete a table, or collection as it is called in MongoDB, by using the drop() method.
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")
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With