Micronaut MongoDB

Integration between Micronaut and MongoDB

Version: 6.0.1

1 Introduction

This project includes integration between Micronaut and MongoDB.

Note that this project provides only low-level access to the MongoDB client drivers (synchronous, reactive streams, and Kotlin coroutine). If you are looking for a more complete experience including support for data access repositories see the documentation for Micronaut Data MongoDB as well as these useful guides:

2 Release History

For this project, you can find a list of releases (with release notes) here:

3 Breaking Changes

Version 5.0.0

Support for testing with flapdoodle has been removed. Please use test-containers instead as described under MongoDB and Testing.

GORM is not supported in Micronaut Framework 4.x. The setup instructions for using it are no longer relevant and have been removed.

4 Setting up the Mongo Driver

Using the CLI

If you are creating your project using the Micronaut CLI, supply the mongo-reactive feature to configure the native MongoDB driver in your project:

$ mn create-app my-app --features mongo-reactive

Micronaut includes a configuration to automatically configure the native MongoDB Java driver. To use this configuration, add the following dependency to your application:

implementation("io.micronaut.mongodb:micronaut-mongo-reactive")
<dependency>
    <groupId>io.micronaut.mongodb</groupId>
    <artifactId>micronaut-mongo-reactive</artifactId>
</dependency>

Then configure the URI of the MongoDB server in application.yml:

Configuring a MongoDB server
mongodb:
    uri: mongodb://username:password@localhost:27017/databaseName
The mongodb.uri follows the MongoDB Connection String format.

A non-blocking Reactive Streams MongoClient is then available for dependency injection.

To use the blocking driver, add a dependency to your application to the micronaut-mongo-sync module.

implementation("io.micronaut.mongodb:micronaut-mongo-sync")
<dependency>
    <groupId>io.micronaut.mongodb</groupId>
    <artifactId>micronaut-mongo-sync</artifactId>
</dependency>

Then the blocking MongoClient will be available for injection.

To use the Kotlin coroutine driver, add a dependency to your application to the micronaut-mongo-coroutine module.

implementation("io.micronaut.mongodb:micronaut-mongo-coroutine")
<dependency>
    <groupId>io.micronaut.mongodb</groupId>
    <artifactId>micronaut-mongo-coroutine</artifactId>
</dependency>

Then the Kotlin coroutine MongoClient will be available for injection.

5 Configuring the Mongo Driver

Micronaut binds MongoDB driver settings directly onto MongoClientSettings.Builder and the nested builder types it exposes, such as cluster, connectionPool, socket, server, and ssl.

For example, in application.yml:

Configuring MongoDB Driver Settings
mongodb:
    uri: mongodb://localhost:27017/app
    readConcern: majority
    connectionPool:
        maxSize: 20

The same configuration model is used for the blocking, reactive streams, and Kotlin coroutine clients. Named clients use the same structure under mongodb.servers.<name>.

See the API for DefaultMongoConfiguration and NamedMongoConfiguration for more information on the available configuration options.

CSFLE and Other Programmatic Settings

Some MongoDB features, including Client-Side Field Level Encryption (CSFLE), require programmatic customization that cannot be expressed as simple configuration properties. For those cases, define one or more MongoClientSettingsBuilderCustomizer beans.

Micronaut applies these customizers after the configuration-backed settings have been bound and before the final MongoClientSettings instance is built. That lets you keep the common driver configuration in application.yml and add CSFLE-specific settings only where the MongoDB Java driver requires programmatic setup.

Use the approach as follows:

  1. Configure the common driver settings such as mongodb.uri, readConcern, and pool options in configuration properties.

  2. Add a MongoClientSettingsBuilderCustomizer bean for the driver-level settings that are not exposed as simple properties, such as AutoEncryptionSettings and uuidRepresentation.

  3. Inspect NamedMongoConfiguration inside the customizer when the CSFLE settings need to vary per named client.

  4. Populate the builder with the KMS providers, key vault namespace, schema map, encrypted fields map, and any extra auto-encryption options required by your deployment.

The example uses the local KMS provider for brevity. Replace that placeholder with the provider configuration that matches your environment.

The same customizer beans apply to the blocking, reactive streams, and coroutine drivers because all clients are created from the same AbstractMongoConfiguration.buildSettings() workflow.

For the Reactive driver, the same configuration properties apply. For example:

Configuring the Reactive Streams Driver
mongodb:
    uri: mongodb://localhost:27017/app
    cluster:
        maxWaitQueueSize: 5

POJO Discriminators

When using MongoDB POJO codecs together with @BsonDiscriminator, configure mongodb.package-names so Micronaut can register the matching types with the MongoDB PojoCodecProvider.

To avoid classpath or JAR scanning, discriminator registration only considers classes that have Micronaut bean introspections. Annotate the root type and subtypes with @Introspected, or otherwise provide bean introspection metadata for those classes.

Configuring packages for discriminator-based POJOs
mongodb.package-names[0]=example.animals
mongodb:
  package-names:
    - example.animals
[mongodb]
  package-names=[
    "example.animals"
  ]
mongodb {
  packageNames = ["example.animals"]
}
{
  mongodb {
    package-names = ["example.animals"]
  }
}
{
  "mongodb": {
    "package-names": ["example.animals"]
  }
}

To keep MongoDB clients available briefly for deferred shutdown work triggered by ApplicationShutdownEvent listeners, enable Micronaut graceful shutdown and set mongodb.shutdown-delay:

micronaut:
  lifecycle:
    graceful-shutdown:
      enabled: true
      grace-period: 5s
mongodb:
  shutdown-delay: 1s

The graceful shutdown grace period must be greater than or equal to mongodb.shutdown-delay.

Multiple MongoDB Drivers

You can create multiple MongoDB connections using the mongodb.servers setting. For example in application.yml:

Configuring Multiple MongoDB Drivers
mongodb:
    servers:
        another:
            uri: mongodb://localhost:27018

With the above configuration in place you can inject a MongoClient using the name another:

import com.mongodb.reactivestreams.client.*;
import jakarta.inject.*;
...
@Inject @Named("another") MongoClient mongoClient;

MongoDB Health Checks

When the mongo-reactive or mongo-coroutine module is activated, the corresponding MongoHealthIndicator or CoroutineMongoHealthIndicator is activated, resulting in the /health endpoint and CurrentHealthStatus interface resolving the health of the MongoDB connection.

See the section on the Health Endpoint for more information.

6 MongoDB and Testing

The MongoDb support in Micronaut Test Resources – which uses the Testcontainers library for Java – is the recommended way to test Mongo interaction.

Alternatively, Testcontainers for Java can be used directly to test Mongo interaction. For Spock tests this is a simple matter of:

@Shared @AutoCleanup GenericContainer mongo =
        new GenericContainer("mongo:4.0")
                .withExposedPorts(27017)

def setupSpec() {
    mongo.start()
}

7 Repository

You can find the source code of this project in this repository: