These tutorials target Micronaut Framework 3. Read, Guides for Micronaut Framework 4.

Micronaut MongoDB Asynchronous

Learn how to use a non-blocking reactive streams MongoDB client with a Micronaut application

Authors: Sergio del Amo

Micronaut Version: 3.9.2

1. Getting Started

In this guide, we will create a Micronaut application written in Groovy.

You will use MongoDB for persistence.

2. What you will need

To complete this guide, you will need the following:

  • Some time on your hands

  • A decent text editor or IDE

  • JDK 1.8 or greater installed with JAVA_HOME configured appropriately

3. Solution

We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.

4. Writing the Application

Create an application using the Micronaut Command Line Interface or with Micronaut Launch.

mn create-app example.micronaut.micronautguide \
    --features=mongo-reactive,reactor,serialization-bson \
    --build=gradle
    --lang=groovy
If you don’t specify the --build argument, Gradle is used as the build tool.
If you don’t specify the --lang argument, Java is used as the language.

The previous command creates a Micronaut application with the default package example.micronaut in a directory named micronautguide.

If you use Micronaut Launch, select Micronaut Application as application type and add mongo-reactive, reactor, and serialization-bson features.

If you have an existing Micronaut application and want to add the functionality described here, you can view the dependency and configuration changes from the specified features and apply those changes to your application.

4.1. POJO

Create Fruit POJO:

src/main/groovy/example/micronaut/Fruit.groovy
package example.micronaut

import groovy.transform.CompileStatic
import io.micronaut.core.annotation.Creator
import io.micronaut.core.annotation.NonNull
import io.micronaut.core.annotation.Nullable
import io.micronaut.serde.annotation.Serdeable
import org.bson.codecs.pojo.annotations.BsonCreator
import org.bson.codecs.pojo.annotations.BsonProperty

import javax.validation.constraints.NotBlank

@CompileStatic
@Serdeable (1)
class Fruit {

    @NonNull
    @NotBlank (2)
    @BsonProperty('name') (3)
    private final String name

    @Nullable
    @BsonProperty('description') (3)
    private final String description

    Fruit(@NonNull String name) {
        this(name, null)
    }

    @Creator (4)
    @BsonCreator(3)
    Fruit(@NonNull @BsonProperty('name') String name,  (3)
          @Nullable @BsonProperty('description') String description) {  (3)
        this.name = name
        this.description = description
    }

    @NonNull
    String getName() {
        name
    }

    @Nullable
    String getDescription() {
        description
    }
}
1 Declare the @Serdeable annotation at the type level in your source code to allow the type to be serialized or deserialized.
2 Use javax.validation.constraints Constraints to ensure the data matches your expectations.
3 Since the POJO does not have an empty constructor, use the annotations @BsonCreator and BsonProperty to define data conversion between BSON and POJO with the MongoDB Java driver. See POJOs without No-Argument Constructor.
4 Annotate with @Creator to provide a hint as to which constructor is the primary constructor.

4.2. Repository

Create a repository interface to encapsulate the CRUD actions for Fruit.

src/main/groovy/example/micronaut/FruitRepository.groovy
package example.micronaut

import io.micronaut.core.annotation.NonNull
import org.reactivestreams.Publisher
import reactor.core.publisher.Mono

import javax.validation.Valid
import javax.validation.constraints.NotNull

interface FruitRepository {

    @NonNull
    Publisher<Fruit> list()

    Mono<Boolean> save(@NonNull @NotNull @Valid Fruit fruit) (1)
}
1 Add @Valid to any method parameter which requires validation.

4.3. Controller

Create FruitController:

src/main/groovy/example/micronaut/FruitController.groovy
package example.micronaut

import groovy.transform.CompileStatic
import io.micronaut.core.annotation.NonNull
import io.micronaut.http.HttpStatus
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.Post
import org.reactivestreams.Publisher
import reactor.core.publisher.Mono

import javax.validation.Valid
import javax.validation.constraints.NotNull

import static io.micronaut.http.HttpStatus.CONFLICT
import static io.micronaut.http.HttpStatus.CREATED

@CompileStatic
@Controller('/fruits') (1)
class FruitController {

    private final FruitRepository fruitService

    FruitController(FruitRepository fruitService) {  (2)
        this.fruitService = fruitService
    }

    @Get (3)
    Publisher<Fruit> list() {
        fruitService.list()
    }

    @Post (4)
    Mono<HttpStatus> save(@NonNull @NotNull @Valid Fruit fruit) { (5)
        fruitService.save(fruit) (6)
                .map(added -> added ? CREATED : CONFLICT)
    }
}
1 The class is defined as a controller with the @Controller annotation mapped to the path /fruits.
2 Use constructor injection to inject a bean of type FruitRepository.
3 The @Get annotation maps the list method to an HTTP GET request on /fruits.
4 The @Post annotation maps the save method to an HTTP POST request on /fruits.
5 Add @Valid to any method parameter which requires validation.
6 Micronaut controller methods can return reactive types

4.4. Configuration

Create a configuration object to encapsulate the MongoDB database name and collection name.

src/main/groovy/example/micronaut/MongoDbConfiguration.groovy
package example.micronaut

import io.micronaut.context.annotation.ConfigurationProperties
import io.micronaut.core.annotation.NonNull
import io.micronaut.core.naming.Named

@ConfigurationProperties('db') (1)
interface MongoDbConfiguration extends Named {

    @NonNull
    String getCollection()
}
1 The @ConfigurationProperties annotation takes the configuration prefix.

Define the values via configuration:

src/main/resources/application.yml
db:
  name: 'fruit'
  collection: 'fruit'

4.5. MongoDB repository

Implement FruitRepository by using a MongoClient

src/main/groovy/example/micronaut/MongoDbFruitRepository.groovy
package example.micronaut

import com.mongodb.reactivestreams.client.MongoClient
import com.mongodb.reactivestreams.client.MongoCollection
import groovy.transform.CompileStatic
import io.micronaut.core.annotation.NonNull
import jakarta.inject.Singleton
import org.reactivestreams.Publisher
import reactor.core.publisher.Mono

import javax.validation.Valid
import javax.validation.constraints.NotNull

@CompileStatic
@Singleton (1)
class MongoDbFruitRepository implements FruitRepository {

    private final MongoDbConfiguration mongoConf
    private final MongoClient mongoClient

    MongoDbFruitRepository(MongoDbConfiguration mongoConf,  (2)
                           MongoClient mongoClient) {  (3)
        this.mongoConf = mongoConf
        this.mongoClient = mongoClient
    }

    @Override
    Mono<Boolean> save(@NonNull @NotNull @Valid Fruit fruit) {
        Mono.from(collection.insertOne(fruit)) (4)
                .map(insertOneResult -> true)
                .onErrorReturn(false)
    }

    @Override
    @NonNull
    Publisher<Fruit> list() {
        collection.find() (4)
    }

    @NonNull
    private MongoCollection<Fruit> getCollection() {
        mongoClient.getDatabase(mongoConf.name)
                .getCollection(mongoConf.collection, Fruit)
    }
}
1 Use jakarta.inject.Singleton to designate a class as a singleton.
2 Use constructor injection to inject a bean of type MongoDbConfiguration.
3 Use constructor injection to inject a bean of type MongoClient.
4 MongoClient methods return reactive sequences.

By using the feature mongo-reactive, the application includes the following dependency:

build.gradle
implementation("io.micronaut.mongodb:micronaut-mongo-reactive")

This registers a non-blocking reactive streams MongoDB client with MongoClient, which you can inject in other Micronaut beans as illustrated in the above code sample.

4.6. Test

Add a Micronaut declarative HTTP Client to src/test to ease the testing of the application’s API.

src/test/groovy/example/micronaut/FruitClient.groovy
package example.micronaut

import io.micronaut.core.annotation.NonNull
import io.micronaut.http.HttpStatus
import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.Post
import io.micronaut.http.client.annotation.Client

import javax.validation.Valid
import javax.validation.constraints.NotNull

@Client('/fruits')
interface FruitClient {

    @Post
    @NonNull
    HttpStatus save(@NonNull @NotNull @Valid Fruit fruit)

    @NonNull
    @Get
    List<Fruit> findAll()
}

By using the feature mongo-sync, the application includes the following test dependencies:

build.gradle
testImplementation("org.testcontainers:junit-jupiter")
testImplementation("org.testcontainers:mongodb")
testImplementation("org.testcontainers:testcontainers")

Test Resources will provide us with a MongoDB instance for local testing and execution.

Create a test:

src/test/groovy/example/micronaut/FruitControllerSpec.groovy
package example.micronaut

import io.micronaut.http.HttpStatus
import io.micronaut.test.extensions.spock.annotation.MicronautTest
import jakarta.inject.Inject
import spock.lang.Specification

import static io.micronaut.http.HttpStatus.CREATED

@MicronautTest
class FruitControllerSpec extends Specification {

    @Inject
    FruitClient fruitClient

    void fruitsEndpointInteractsWithMongo() {

        when:
        List<Fruit> fruits = fruitClient.findAll()

        then:
        !fruits

        when:
        HttpStatus status = fruitClient.save(new Fruit('banana'))

        then:
        CREATED == status

        when:
        fruits = fruitClient.findAll()

        then:
        fruits
        'banana' == fruits[0].name
        null == fruits[0].description

        when:
        status = fruitClient.save(new Fruit('Apple', 'Keeps the doctor away'))

        then:
        CREATED == status

        when:
        fruits = fruitClient.findAll()

        then:
        fruits.find { it.description == 'Keeps the doctor away' }
    }
}

5. Test Resources

When the application is started locally — either under test or by running the application — resolution of the property mongodb.uri is detected and the Test Resources service will start a local MongoDB docker container, and inject the properties required to use this as the datasource.

When running under production, you should replace this property with the location of your production MongoDB instance via an environment variable.

MONGODB_URI=mongodb://username:password@production-server:27017/databaseName

6. Testing the Application

To run the tests:

./gradlew test

Then open build/reports/tests/test/index.html in a browser to see the results.

7. Running the Application

To run the application, use the ./gradlew run command, which starts the application on port 8080.

curl -d '{"name":"Pear"}'
     -H "Content-Type: application/json"
     -X POST http://localhost:8080/fruits
curl -i localhost:8080/fruits
HTTP/1.1 200 OK
date: Wed, 15 Sep 2021 12:40:15 GMT
Content-Type: application/json
content-length: 110
connection: keep-alive

[{"name":"Pear"}]
curl -d '{"name":"Pear"}'
     -H "Content-Type: application/json"
     -X POST http://localhost:8080/fruits
curl -i localhost:8080/fruits
HTTP/1.1 200 OK
date: Wed, 15 Sep 2021 12:40:15 GMT
Content-Type: application/json
content-length: 110
connection: keep-alive

[{"name":"Pear"}]

8. Next steps

Explore more features with Micronaut Guides.

9. Next Steps

10. Help with the Micronaut Framework

The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.