In MongoDB 2 , a database object (of type com.mongodb.DB ) existed on the collectionExists method, which checked for the existence of a collection with the specified name. But in MongoDB 3, instead of the com.mongodb.DB type, com.mongodb.DB proposed to use the com.mongodb.client.MongoDatabase type, which does not have such a method.

How in MongoDB 3 to check the existence of a collection in the database?

    1 answer 1

    To check the existence of a collection in a database in the case of MongoDB 3, you can use the listCollectionNames method, which returns an iterable set of database collection names. The following fairly simple method is suitable for checking existence:

     /** * Проверка существования в базе данных коллекции с указанным именем. * * @param db База данных. * @param collectionName Имя искомой коллекции. * @return {@code true}, если коллекция существует в базе данных * и {@code false} в противном случае. */ public static boolean hasCollection(final MongoDatabase db, final String collectionName) { assert db != null; assert collectionName != null && !collectionName.isEmpty(); try (final MongoCursor<String> cursor = db.listCollectionNames().iterator()) { while (cursor.hasNext()) if (cursor.next().equals(collectionName)) return true; } return false; } 

    PS Use the "try with resources" construct, introduced in Java 7 .