Databases and Collections

MongoDB stores documents in collections; the collections in databases.



Always check for errors in any SingleResultCallback<T> implementation and handle them appropriately.

For sake of brevity, this tutorial omits the error check logic in the code examples.


  • Include the following import statements:

    import com.mongodb.Block;
    import com.mongodb.async.SingleResultCallback;
    import com.mongodb.async.client.MongoClient;
    import com.mongodb.async.client.MongoClients;
    import com.mongodb.async.client.MongoCollection;
    import com.mongodb.async.client.MongoDatabase;
    import com.mongodb.client.model.CreateCollectionOptions;
    import com.mongodb.client.model.Filters;
    import com.mongodb.client.model.ValidationOptions;
    import org.bson.Document;
  • The following callback:

    SingleResultCallback<Void> callbackWhenFinished = new SingleResultCallback<Void>() {
        public void onResult(final Void result, final Throwable t) {
            System.out.println("Operation Finished!");

Connect to a MongoDB Deployment

Connect to a running MongoDB deployment.

For example, include the following code to connect to a standalone MongoDB deployment running on localhost on port 27017.

MongoClient mongoClient = MongoClients.create();

For additional information on connecting to MongoDB, see Connect to MongoDB.

Access a Database

Once you have a MongoClient instance connected to a MongoDB deployment, use its getDatabase() method to access a database.

Specify the name of the database to the getDatabase() method. If a database does not exist, MongoDB creates the database when you first store data for that database.

The following example accesses the test database:

MongoDatabase database = mongoClient.getDatabase("test");

MongoDatabase instances are immutable.

Get A List of Databases

You can get a list of the available databases using the MongoClient instance’s listDatabaseNames method.

mongoClient.listDatabaseNames().forEach(new Block<String>() {
    public void apply(final String s) {
}, callbackWhenFinished);

Drop A Database

You can drop the current database using its drop:


Access a Collection

Once you have a MongoDatabase instance, use its getCollection() method to access a collection.

Specify the name of the collection to the getCollection() method.

For example, using the database instance, the following statement accesses the collection named myTestCollection:

MongoCollection<Document> coll = database.getCollection("myTestCollection");

MongoCollection instances are immutable.

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.

Explicitly Create a Collection

The async driver provides the createCollection method to explicitly create a collection. When you explicitly create a collection, you can specify various collection options, such as a maximum size or the documentation validation rules, with the CreateCollectionOptions class. If you are not specifying these options, you do not need to explicitly create the collection since MongoDB creates new collections when you first store data for the collections.

Capped Collection

For example, the following operation creates a capped collection sized to 1 megabyte:

          new CreateCollectionOptions().capped(true).sizeInBytes(0x100000),

Document Validation

MongoDB provides the capability to validate documents during updates and insertions. Validation rules are specified on a per-collection basis using the ValidationOptions, which takes a filter document that specifies the validation rules or expressions.

ValidationOptions collOptions = new ValidationOptions().validator(
        Filters.or(Filters.exists("email"), Filters.exists("phone")));
        new CreateCollectionOptions().validationOptions(collOptions),

Get A List of Collections

You can get a list of the collections in a database using the MongoDatabase.listCollectionNames() method:

database.listCollectionNames().forEach(new Block<String>() {
    public void apply(final String name) {
}, callbackWhenFinished);

Drop a Collection

You can drop a collection by using the MongoCollection.drop() method: