The MongoDB Synchronous Driver for Java providing blocking I/O patterns for database operations
—
Database-level operations including collection management, database commands, administrative operations, and database-level aggregation and change streams.
Primary interface for database-level operations providing collection management and database command execution.
/**
* Interface for database-level MongoDB operations
*/
public interface MongoDatabase {
/**
* Gets the name of this database
* @return the database name
*/
String getName();
/**
* Gets a collection with default Document type
* @param collectionName the name of the collection
* @return MongoCollection instance for Document operations
*/
MongoCollection<Document> getCollection(String collectionName);
/**
* Gets a typed collection for custom document classes
* @param collectionName the name of the collection
* @param documentClass the class to decode each document to
* @return MongoCollection instance for typed operations
*/
<TDocument> MongoCollection<TDocument> getCollection(String collectionName, Class<TDocument> documentClass);
/**
* Executes a database command
* @param command the command to execute as Bson
* @return command result as Document
*/
Document runCommand(Bson command);
/**
* Executes a database command with a specific session
* @param clientSession the session to use for the operation
* @param command the command to execute as Bson
* @return command result as Document
*/
Document runCommand(ClientSession clientSession, Bson command);
/**
* Executes a database command with read preference
* @param command the command to execute as Bson
* @param readPreference the read preference for the operation
* @return command result as Document
*/
Document runCommand(Bson command, ReadPreference readPreference);
/**
* Executes a database command returning a specific type
* @param command the command to execute as Bson
* @param clazz the class to decode the result to
* @return command result as specified type
*/
<TResult> TResult runCommand(Bson command, Class<TResult> clazz);
}Usage Examples:
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoCollection;
import org.bson.Document;
// Get collections
MongoCollection<Document> products = database.getCollection("products");
MongoCollection<User> users = database.getCollection("users", User.class);
// Execute database commands
Document stats = database.runCommand(new Document("dbStats", 1));
System.out.println("Database size: " + stats.getInteger("dataSize"));
// Create index command
Document createIndexCmd = new Document("createIndexes", "products")
.append("indexes", Arrays.asList(
new Document("key", new Document("category", 1)).append("name", "category_1")
));
database.runCommand(createIndexCmd);Operations for creating, listing, and managing collections within a database.
/**
* Creates a new collection with default options
* @param collectionName the name of the collection to create
*/
void createCollection(String collectionName);
/**
* Creates a new collection with specific options
* @param collectionName the name of the collection to create
* @param createCollectionOptions options for collection creation
*/
void createCollection(String collectionName, CreateCollectionOptions createCollectionOptions);
/**
* Creates a new collection with session support
* @param clientSession the session to use for the operation
* @param collectionName the name of the collection to create
* @param createCollectionOptions options for collection creation
*/
void createCollection(ClientSession clientSession, String collectionName, CreateCollectionOptions createCollectionOptions);
/**
* Creates a view based on an aggregation pipeline
* @param viewName the name of the view to create
* @param viewOn the source collection or view name
* @param pipeline the aggregation pipeline that defines the view
*/
void createView(String viewName, String viewOn, List<? extends Bson> pipeline);
/**
* Creates a view with additional options
* @param viewName the name of the view to create
* @param viewOn the source collection or view name
* @param pipeline the aggregation pipeline that defines the view
* @param createViewOptions options for view creation
*/
void createView(String viewName, String viewOn, List<? extends Bson> pipeline, CreateViewOptions createViewOptions);
/**
* Drops this database and all its collections
*/
void drop();
/**
* Lists all collection names in this database
* @return iterable of collection names
*/
ListCollectionNamesIterable listCollectionNames();
/**
* Lists collections with full metadata
* @return iterable of collection information documents
*/
ListCollectionsIterable<Document> listCollections();
/**
* Lists collections returning custom type
* @param clazz the class to decode each collection document to
* @return iterable of collection information objects
*/
<TResult> ListCollectionsIterable<TResult> listCollections(Class<TResult> clazz);Usage Examples:
import com.mongodb.client.model.CreateCollectionOptions;
import com.mongodb.client.model.ValidationOptions;
// Create simple collection
database.createCollection("products");
// Create collection with options
ValidationOptions validation = new ValidationOptions()
.validator(Filters.exists("name"));
CreateCollectionOptions options = new CreateCollectionOptions()
.validationOptions(validation)
.capped(true)
.maxDocuments(1000);
database.createCollection("logs", options);
// Create view
List<Bson> pipeline = Arrays.asList(
Aggregates.match(Filters.eq("status", "published")),
Aggregates.project(Projections.include("title", "author", "publishDate"))
);
database.createView("publishedArticles", "articles", pipeline);
// List collections
for (String collectionName : database.listCollectionNames()) {
System.out.println("Collection: " + collectionName);
}
// List with metadata
for (Document collectionInfo : database.listCollections()) {
System.out.println("Collection: " + collectionInfo.toJson());
}Aggregation operations that work across multiple collections in the database.
/**
* Creates an aggregation pipeline for database-level operations
* @param pipeline the aggregation pipeline
* @return AggregateIterable for executing the pipeline
*/
AggregateIterable<Document> aggregate(List<? extends Bson> pipeline);
/**
* Creates an aggregation pipeline returning custom type
* @param pipeline the aggregation pipeline
* @param clazz the class to decode each result document to
* @return AggregateIterable for executing the pipeline
*/
<TResult> AggregateIterable<TResult> aggregate(List<? extends Bson> pipeline, Class<TResult> clazz);
/**
* Creates an aggregation pipeline with session support
* @param clientSession the session to use for the operation
* @param pipeline the aggregation pipeline
* @return AggregateIterable for executing the pipeline
*/
AggregateIterable<Document> aggregate(ClientSession clientSession, List<? extends Bson> pipeline);Usage Examples:
import com.mongodb.client.model.Aggregates;
import com.mongodb.client.model.Accumulators;
// Database-level aggregation across collections
List<Bson> pipeline = Arrays.asList(
// Use $listCollections to get collection info
Aggregates.listCollections(),
Aggregates.match(Filters.eq("type", "collection")),
Aggregates.group(null, Accumulators.sum("totalCollections", 1))
);
for (Document result : database.aggregate(pipeline)) {
System.out.println("Total collections: " + result.getInteger("totalCollections"));
}
// Cross-collection operations with $lookup
List<Bson> crossCollectionPipeline = Arrays.asList(
// Start from one collection
Aggregates.match(Filters.eq("status", "active")),
// Lookup data from another collection
Aggregates.lookup("orders", "_id", "userId", "userOrders"),
Aggregates.project(Projections.include("name", "email", "userOrders"))
);Monitor changes across all collections in a database.
/**
* Creates a change stream to monitor all collections in the database
* @return ChangeStreamIterable for monitoring database changes
*/
ChangeStreamIterable<Document> watch();
/**
* Creates a change stream with aggregation pipeline
* @param pipeline aggregation pipeline to filter changes
* @return ChangeStreamIterable with filtering
*/
ChangeStreamIterable<Document> watch(List<? extends Bson> pipeline);
/**
* Creates a change stream returning custom type
* @param pipeline aggregation pipeline to filter changes
* @param clazz the class to decode each change document to
* @return ChangeStreamIterable with custom type
*/
<TResult> ChangeStreamIterable<TResult> watch(List<? extends Bson> pipeline, Class<TResult> clazz);
/**
* Creates a change stream with session support
* @param clientSession the session to use for the operation
* @param pipeline aggregation pipeline to filter changes
* @return ChangeStreamIterable with session support
*/
ChangeStreamIterable<Document> watch(ClientSession clientSession, List<? extends Bson> pipeline);Usage Examples:
// Monitor all changes in database
try (var cursor = database.watch().cursor()) {
while (cursor.hasNext()) {
ChangeStreamDocument<Document> change = cursor.next();
System.out.println("Collection: " + change.getNamespace().getCollectionName());
System.out.println("Operation: " + change.getOperationType());
System.out.println("Document: " + change.getFullDocument());
}
}
// Monitor specific operations with filter
List<Bson> pipeline = Arrays.asList(
Aggregates.match(Filters.in("operationType", Arrays.asList("insert", "update")))
);
try (var cursor = database.watch(pipeline).cursor()) {
while (cursor.hasNext()) {
ChangeStreamDocument<Document> change = cursor.next();
System.out.println("Change detected: " + change.getOperationType());
}
}Database instances support configuration chaining for operation customization.
/**
* Creates a new database instance with a different codec registry
* @param codecRegistry the codec registry for encoding/decoding
* @return new MongoDatabase instance with specified codec registry
*/
MongoDatabase withCodecRegistry(CodecRegistry codecRegistry);
/**
* Creates a new database instance with a different read preference
* @param readPreference the read preference for operations
* @return new MongoDatabase instance with specified read preference
*/
MongoDatabase withReadPreference(ReadPreference readPreference);
/**
* Creates a new database instance with a different write concern
* @param writeConcern the write concern for operations
* @return new MongoDatabase instance with specified write concern
*/
MongoDatabase withWriteConcern(WriteConcern writeConcern);
/**
* Creates a new database instance with a different read concern
* @param readConcern the read concern for operations
* @return new MongoDatabase instance with specified read concern
*/
MongoDatabase withReadConcern(ReadConcern readConcern);
/**
* Creates a new database instance with a timeout
* @param timeout the timeout for operations
* @param timeUnit the time unit for the timeout
* @return new MongoDatabase instance with specified timeout
*/
MongoDatabase withTimeout(long timeout, TimeUnit timeUnit);Usage Examples:
import com.mongodb.ReadPreference;
import com.mongodb.WriteConcern;
import com.mongodb.ReadConcern;
// Configure database for specific requirements
MongoDatabase configuredDb = database
.withReadPreference(ReadPreference.secondaryPreferred())
.withWriteConcern(WriteConcern.MAJORITY)
.withReadConcern(ReadConcern.SNAPSHOT);
// Use configured database
MongoCollection<Document> collection = configuredDb.getCollection("important-data");Install with Tessl CLI
npx tessl i tessl/maven-org-mongodb--mongodb-driver-sync