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 .