Access a MongoDB database with Micronaut Data MongoDB

Learn how to access a MongoDB database with Micronaut Data and the MongoDB Sync driver.

Authors: Tim Yates

Micronaut Version: 5.0.2

1. Getting Started

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

You will use MongoDB for persistence.

2. What you will need

To complete this guide, you will need the following:

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=data-mongodb \
    --build=gradle \
    --lang=kotlin \
    --test=junit
If you don’t specify the --build argument, Gradle with the Kotlin DSL is used as the build tool.
If you don’t specify the --lang argument, Java is used as the language.
If you don’t specify the --test argument, JUnit is used for Java and Kotlin, and Spock is used for Groovy.

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 data-mongodb 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. Dependencies

In this guide, we use the MongoDB Sync driver.

The data-mongodb feature adds the following dependencies:

build.gradle
kapt("io.micronaut.data:micronaut-data-document-processor")
implementation("io.micronaut.data:micronaut-data-mongodb")
runtimeOnly("org.mongodb:mongodb-driver-sync")