/**
* Returns a set containing the names of all collections in this database.
* @return the names of collections in this database
* @throws MongoException if the operation failed
* @mongodb.driver.manual reference/method/db.getCollectionNames/ getCollectionNames()
public Set<String> getCollectionNames() {
List<String> collectionNames =
new MongoIterableImpl<DBObject>(null, executor, ReadConcern.DEFAULT, primary()) {
@Override
public ReadOperation<BatchCursor<DBObject>> asReadOperation() {
return new ListCollectionsOperation<DBObject>(name, commandCodec)
.nameOnly(true);
}.map(new Function<DBObject, String>() {
@Override
public String apply(final DBObject result) {
return (String) result.get("name");
}).into(new ArrayList<String>());
Collections.sort(collectionNames);
return new LinkedHashSet<String>(collectionNames);
@Nullable @Override public V first() { U first = iterable.first(); if (first == null) { return null; return mapper.apply(first);
/**
* Creates a new {@link CloseableIterableCursorAdapter} backed by the given {@link Cursor}.
* @param cursor
* @param exceptionTranslator
* @param objectReadCallback
public CloseableIterableCursorAdapter(MongoIterable<Document> cursor,
PersistenceExceptionTranslator exceptionTranslator, DocumentCallback<T> objectReadCallback) {
this.cursor = cursor.iterator();
this.exceptionTranslator = exceptionTranslator;
this.objectReadCallback = objectReadCallback;
DefaultDbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory);
result = result.map((source) -> converter.mapValueToTargetType(source,
getMostSpecificConversionTargetType(resultClass, entityClass, field), dbRefResolver));
return (List<T>) result.into(new ArrayList<>());
} catch (RuntimeException e) {
throw potentiallyConvertRuntimeException(e, exceptionTranslator);
/**
* Checks that the documents iterator have one document only.
* @param documents documents
private Optional<Document> limitOne(MongoIterable<Document> documents) {
Document first = documents.first();
try (MongoCursor<Document> iterator = documents.iterator()) {
if (iterator.hasNext()) {
iterator.next();
if (iterator.hasNext()) {
throw new DlabException("too many items found while one is expected");
return Optional.ofNullable(first);
@Override public void forEach(final Block<? super V> block) { iterable.forEach(new Block<U>() { @Override public void apply(final U document) { block.apply(mapper.apply(document));
@Override public MappingIterable<U, V> batchSize(final int batchSize) { iterable.batchSize(batchSize); return this;
private boolean databaseContainsCollection(String collection) {
return StreamSupport.stream(mongoDatabase.listCollectionNames().spliterator(), false)
.anyMatch(collection::equals);
DefaultDbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory);
result = result.map((source) -> converter.mapValueToTargetType(source,
getMostSpecificConversionTargetType(resultClass, entityClass, field), dbRefResolver));
return (List<T>) result.into(new ArrayList<>());
} catch (RuntimeException e) {
throw potentiallyConvertRuntimeException(e, exceptionTranslator);
@Override public void forEach(final Block<? super V> block) { iterable.forEach(new Block<U>() { @Override public void apply(final U document) { block.apply(mapper.apply(document));
@Override public MappingIterable<U, V> batchSize(final int batchSize) { iterable.batchSize(batchSize); return this;
/** * Check if the collection exists and if it is not empty * @param mongoDatabase the Mongo database * @param collection the collection name * @return true if the collection exists and not empty, false otherwise public static boolean hasCollection(MongoDatabase mongoDatabase, String collection) { MongoIterable<String> collections = mongoDatabase.listCollectionNames(); boolean found = StreamSupport.stream(collections.spliterator(), false).anyMatch(collection::equals); return found && mongoDatabase.getCollection(collection).count() > 0;
/**
* Gets a list of the names of all databases on the connected server.
* @return list of database names
* @throws MongoException if the operation fails
* @deprecated Replaced with {@link com.mongodb.MongoClient#listDatabaseNames()}
@Deprecated
public List<String> getDatabaseNames() {
return new MongoIterableImpl<DBObject>(null, createOperationExecutor(), ReadConcern.DEFAULT, primary()) {
@Override
public ReadOperation<BatchCursor<DBObject>> asReadOperation() {
return new ListDatabasesOperation<DBObject>(MongoClient.getCommandCodec());
}.map(new Function<DBObject, String>() {
@Override
public String apply(final DBObject result) {
return (String) result.get("name");
}).into(new ArrayList<String>());
@Override public MongoCursor<V> iterator() { return new MongoMappingCursor<U, V>(iterable.iterator(), mapper);
@Signature public Document first() { return getWrappedObject().first();
public static void cleanDatabase(MongoPrimary primary, String dbName) { primary.execute("clean-db", mongo -> { MongoDatabase db1 = mongo.getDatabase(dbName); db1.listCollectionNames().forEach((Consumer<String>) ((String x) -> { logger.info("Removing collection '{}' from database '{}'", x, dbName); db1.getCollection(x).drop();
@Signature public WrapMongoIterable batchSize(Environment env, int size) { MongoIterable<Document> documents = getWrappedObject().batchSize(size); return new WrapMongoIterable(env, documents);
private MongoCollection<MongoBlob> initBlobCollection(MongoDatabase db) {
if (stream(db.listCollectionNames().spliterator(), false)
.noneMatch(COLLECTION_BLOBS::equals)) {
db.createCollection(COLLECTION_BLOBS);
// override the read preference configured with the MongoDB URI
// and use the primary as default. Reading a blob will still
// try a secondary first and then fallback to the primary.
return db.getCollection(COLLECTION_BLOBS, MongoBlob.class)
.withCodecRegistry(CODEC_REGISTRY)
.withReadPreference(primary());
});
return new AggregationResults<>(iterable.into(new ArrayList<>()),
new Document("results", rawResult).append("ok", 1.0D));
@Override public MongoCursor<V> iterator() { return new MongoMappingCursor<U, V>(iterable.iterator(), mapper);