Back to Guides

Using the MongoDB Client

MongoDB is a well known NoSQL Database that is widely used.

In this guide, we see how you can get your REST services to use the MongoDB database.

Prerequisites

To complete this guide, you need:

  • Roughly 15 minutes

  • An IDE

  • JDK 11+ installed with JAVA_HOME configured appropriately

  • Apache Maven 3.8.6

  • Optionally the Quarkus CLI if you want to use it

  • Optionally Mandrel or GraalVM installed and configured appropriately if you want to build a native executable (or Docker if you use a native container build)

  • MongoDB installed or Docker installed

Architecture

The application built in this guide is quite simple: the user can add elements in a list using a form and the list is updated.

All the information between the browser and the server is formatted as JSON.

The elements are stored in MongoDB.

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.

Clone the Git repository: git clone https://github.com/quarkusio/quarkus-quickstarts.git, or download an archive.

The solution is located in the mongodb-quickstart directory.

Creating the Maven project

First, we need a new project. Create a new project with the following command:

CLI
quarkus create app org.acme:mongodb-quickstart \
    --extension='resteasy-reactive-jackson,mongodb-client' \
    --no-code
cd mongodb-quickstart

To create a Gradle project, add the --gradle or --gradle-kotlin-dsl option.

For more information about how to install the Quarkus CLI and use it, please refer to the Quarkus CLI guide.

Maven
mvn io.quarkus.platform:quarkus-maven-plugin:2.14.2.Final:create \
    -DprojectGroupId=org.acme \
    -DprojectArtifactId=mongodb-quickstart \
    -Dextensions='resteasy-reactive-jackson,mongodb-client' \
    -DnoCode
cd mongodb-quickstart

To create a Gradle project, add the -DbuildTool=gradle or -DbuildTool=gradle-kotlin-dsl option.

This command generates a Maven structure importing the RESTEasy Reactive Jackson and MongoDB Client extensions. After this, the quarkus-mongodb-client extension has been added to your build file.

If you already have your Quarkus project configured, you can add the mongodb-client extension to your project by running the following command in your project base directory:

CLI
quarkus extension add 'mongodb-client'
Maven
./mvnw quarkus:add-extension -Dextensions='mongodb-client'
Gradle
./gradlew addExtension --extensions='mongodb-client'

This will add the following to your pom.xml:

pom.xml
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-mongodb-client</artifactId>
</dependency>
build.gradle
implementation("io.quarkus:quarkus-mongodb-client")

Creating your first JSON REST service

In this example, we will create an application to manage a list of fruits.

First, let’s create the Fruit bean as follows:

package org.acme.mongodb;

import java.util.Objects;

public class Fruit {

    private String name;
    private String description;
    private String id;

    public Fruit() {
    }

    public Fruit(String name, String description) {
        this.name = name;
        this.description = description;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof Fruit)) {
            return false;
        }

        Fruit other = (Fruit) obj;

        return Objects.equals(other.name, this.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(this.name);
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getId() {
        return id;
    }
}

Nothing fancy. One important thing to note is that having a default constructor is required by the JSON serialization layer.

Now create a org.acme.mongodb.FruitService that will be the business layer of our application and store/load the fruits from the mongoDB database.

package org.acme.mongodb;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import org.bson.Document;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;

@ApplicationScoped
public class FruitService {

    @Inject MongoClient mongoClient;

    public List<Fruit> list(){
        List<Fruit> list = new ArrayList<>();
        MongoCursor<Document> cursor = getCollection().find().iterator();

        try {
            while (cursor.hasNext()) {
                Document document = cursor.next();
                Fruit fruit = new Fruit();
                fruit.setName(document.getString("name"));
                fruit.setDescription(document.getString("description"));
                list.add(fruit);
            }
        } finally {
            cursor.close();
        }
        return list;
    }

    public void add(Fruit fruit){
        Document document = new Document()
                .append("name", fruit.getName())
                .append("description", fruit.getDescription());
        getCollection().insertOne(document);
    }

    private MongoCollection getCollection(){
        return mongoClient.getDatabase("fruit").getCollection("fruit");
    }
}

Now, create the org.acme.mongodb.FruitResource class as follows:

@Path("/fruits")
public class FruitResource {

    @Inject FruitService fruitService;

    @GET
    public List<Fruit> list() {
        return fruitService.list();
    }

    @POST
    public List<Fruit> add(Fruit fruit) {
        fruitService.add(fruit);
        return list();
    }
}

The implementation is pretty straightforward, and you just need to define your endpoints using the JAX-RS annotations and use the FruitService to list/add new fruits.

Configuring the MongoDB database

The main property to configure is the URL to access to MongoDB. Almost all configuration can be included in the connection URI, so we advise you to do so. You can find more information in the MongoDB documentation: https://docs.mongodb.com/manual/reference/connection-string/

A sample configuration should look like this:

# configure the mongoDB client for a replica set of two nodes
quarkus.mongodb.connection-string = mongodb://mongo1:27017,mongo2:27017

In this example, we are using a single instance running on localhost:

# configure the mongoDB client for a single instance on localhost
quarkus.mongodb.connection-string = mongodb://localhost:27017

If you need more configuration properties, there is a full list at the end of this guide.

By default, Quarkus will restrict the use of JNDI within an application, as a precaution to try and mitigate any future vulnerabilities similar to Log4Shell. Because the mongo+srv protocol often used to connect to MongoDB requires JNDI, this protection is automatically disabled when using the MongoDB client extension.

Dev Services (Configuration Free Databases)

Quarkus supports a feature called Dev Services that allows you to create various datasources without any config. In the case of MongoDB this support extends to the default MongoDB connection. What that means practically, is that if you have not configured quarkus.mongodb.connection-string, Quarkus will automatically start a MongoDB container when running tests or in dev mode, and automatically configure the connection.

MongoDB Dev Services is based on Testcontainers MongoDB module that will start a single node replicaset.

When running the production version of the application, the MongoDB connection need to be configured as normal, so if you want to include a production database config in your application.properties and continue to use Dev Services we recommend that you use the %prod. profile to define your MongoDB settings.

Configuration property fixed at build time - All other configuration properties are overridable at runtime

Configuration property

Type

Default

If DevServices has been explicitly enabled or disabled. DevServices is generally enabled by default, unless there is an existing configuration present. When DevServices is enabled Quarkus will attempt to automatically configure and start a database when running in Dev or Test mode.

Environment variable: QUARKUS_MONGODB_DEVSERVICES_ENABLED

boolean

The container image name to use, for container based DevServices providers.

Environment variable: QUARKUS_MONGODB_DEVSERVICES_IMAGE_NAME

string

Optional fixed port the dev service will listen to. If not defined, the port will be chosen randomly.

Environment variable: QUARKUS_MONGODB_DEVSERVICES_PORT

int

Generic properties that are added to the connection URL.

Environment variable: QUARKUS_MONGODB_DEVSERVICES_PROPERTIES

Map<String,String>

Multiple MongoDB Clients

MongoDB allows you to configure multiple clients. Using several clients works the same way as having a single client.

quarkus.mongodb.connection-string = mongodb://login:pass@mongo1:27017/database

quarkus.mongodb.users.connection-string = mongodb://mongo2:27017/userdb
quarkus.mongodb.inventory.connection-string = mongodb://mongo3:27017/invdb,mongo4:27017/invdb

Notice there’s an extra bit in the key (the users and inventory segments). The syntax is as follows: quarkus.mongodb.[optional name.][mongo connection property]. If the name is omitted, it configures the default client.

The use of multiple MongoDB clients enables multi-tenancy for MongoDB by allowing to connect to multiple MongoDB clusters.
If you want to connect to multiple databases inside the same cluster, multiple clients are not necessary as a single client is able to access all databases in the same cluster (as a JDBC connection is able to access to multiple schemas inside the same database).

Named Mongo client Injection

When using multiple clients, each MongoClient, you can select the client to inject using the io.quarkus.mongodb.MongoClientName qualifier. Using the above properties to configure three different clients, you can also inject each one as follows:

@Inject
MongoClient defaultMongoClient;

@Inject
@MongoClientName("users")
MongoClient mongoClient1;

@Inject
@MongoClientName("inventory")
ReactiveMongoClient mongoClient2;

Running a MongoDB Database

As by default, MongoClient is configured to access a local MongoDB database on port 27017 (the default MongoDB port), if you have a local running database on this port, there is nothing more to do before being able to test it!

If you want to use Docker to run a MongoDB database, you can use the following command to launch one:

docker run -ti --rm -p 27017:27017 mongo:4.4

If you use Dev Services, launching the container manually is not necessary!

Creating a frontend

Now let’s add a simple web page to interact with our FruitResource. Quarkus automatically serves static resources located under the META-INF/resources directory. In the src/main/resources/META-INF/resources directory, add a fruits.html file with the content from this fruits.html file in it.

You can now interact with your REST service:

  • start Quarkus with:

    CLI
    quarkus dev
    Maven
    ./mvnw quarkus:dev
    Gradle
    ./gradlew --console=plain quarkusDev
  • open a browser to http://localhost:8080/fruits.html

  • add new fruits to the list via the form

Reactive MongoDB Client

A reactive MongoDB Client is included in Quarkus. Using it is as easy as using the classic MongoDB Client. You can rewrite the previous example to use it like the following.

Mutiny

The MongoDB reactive client uses Mutiny reactive types. If you are not familiar with Mutiny, check Mutiny - an intuitive reactive programming library.

package org.acme.mongodb;

import io.quarkus.mongodb.reactive.ReactiveMongoClient;
import io.quarkus.mongodb.reactive.ReactiveMongoCollection;
import io.smallrye.mutiny.Uni;
import org.bson.Document;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.List;

@ApplicationScoped
public class ReactiveFruitService {

    @Inject
    ReactiveMongoClient mongoClient;

    public Uni<List<Fruit>> list() {
        return getCollection().find()
                .map(doc -> {
                    Fruit fruit = new Fruit();
                    fruit.setName(doc.getString("name"));
                    fruit.setDescription(doc.getString("description"));
                    return fruit;
                }).collect().asList();
    }

    public Uni<Void> add(Fruit fruit) {
        Document document = new Document()
                .append("name", fruit.getName())
                .append("description", fruit.getDescription());
        return getCollection().insertOne(document)
                .onItem().ignore().andContinueWithNull();
    }

    private ReactiveMongoCollection<Document> getCollection() {
        return mongoClient.getDatabase("fruit").getCollection("fruit");
    }
}
package org.acme.mongodb;

import io.smallrye.mutiny.Uni;

import java.util.List;

import javax.inject.Inject;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.core.MediaType;

@Path("/reactive_fruits")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class ReactiveFruitResource {

    @Inject
    ReactiveFruitService fruitService;

    @GET
    public Uni<List<Fruit>> list() {
        return fruitService.list();
    }

    @POST
    public Uni<List<Fruit>> add(Fruit fruit) {
        return fruitService.add(fruit)
                .onItem().ignore().andSwitchTo(this::list);
    }
}

Simplifying MongoDB Client usage using BSON codec

By using a Bson Codec, the MongoDB Client will take care of the transformation of your domain object to/from a MongoDB Document automatically.

First you need to create a Bson Codec that will tell Bson how to transform your entity to/from a MongoDB Document. Here we use a CollectibleCodec as our object is retrievable from the database (it has a MongoDB identifier), if not we would have used a Codec instead. More information in the codec documentation: https://www.mongodb.com/docs/drivers/java/sync/current/fundamentals/data-formats/codecs/.

package org.acme.mongodb.codec;

import com.mongodb.MongoClientSettings;
import org.acme.mongodb.Fruit;
import org.bson.Document;
import org.bson.BsonWriter;
import org.bson.BsonValue;
import org.bson.BsonReader;
import org.bson.BsonString;
import org.bson.codecs.Codec;
import org.bson.codecs.CollectibleCodec;
import org.bson.codecs.DecoderContext;
import org.bson.codecs.EncoderContext;

import java.util.UUID;

public class FruitCodec implements CollectibleCodec<Fruit> {

    private final Codec<Document> documentCodec;

    public FruitCodec() {
        this.documentCodec = MongoClientSettings.getDefaultCodecRegistry().get(Document.class);
    }

    @Override
    public void encode(BsonWriter writer, Fruit fruit, EncoderContext encoderContext) {
        Document doc = new Document();
        doc.put("name", fruit.getName());
        doc.put("description", fruit.getDescription());
        documentCodec.encode(writer, doc, encoderContext);
    }

    @Override
    public Class<Fruit> getEncoderClass() {
        return Fruit.class;
    }

    @Override
    public Fruit generateIdIfAbsentFromDocument(Fruit document) {
        if (!documentHasId(document)) {
            document.setId(UUID.randomUUID().toString());
        }
        return document;
    }

    @Override
    public boolean documentHasId(Fruit document) {
        return document.getId() != null;
    }

    @Override
    public BsonValue getDocumentId(Fruit document) {
        return new BsonString(document.getId());
    }

    @Override
    public Fruit decode(BsonReader reader, DecoderContext decoderContext) {
        Document document = documentCodec.decode(reader, decoderContext);
        Fruit fruit = new Fruit();
        if (document.getString("id") != null) {
            fruit.setId(document.getString("id"));
        }
        fruit.setName(document.getString("name"));
        fruit.setDescription(document.getString("description"));
        return fruit;
    }
}

Then you need to create a CodecProvider to link this Codec to the Fruit class.

package org.acme.mongodb.codec;

import org.acme.mongodb.Fruit;
import org.bson.codecs.Codec;
import org.bson.codecs.configuration.CodecProvider;
import org.bson.codecs.configuration.CodecRegistry;

public class FruitCodecProvider implements CodecProvider {
    @Override
    public <T> Codec<T> get(Class<T> clazz, CodecRegistry registry) {
        if (clazz.equals(Fruit.class)) {
            return (Codec<T>) new FruitCodec();
        }
        return null;
    }

}

Quarkus takes care of registering the CodecProvider for you as a CDI bean of @Singleton scope.

Finally, when getting the MongoCollection from the database you can use directly the Fruit class instead of the Document one, the codec will automatically map the Document to/from your Fruit class.

Here is an example of using a MongoCollection with the FruitCodec.

package org.acme.mongodb;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;

@ApplicationScoped
public class CodecFruitService {

    @Inject MongoClient mongoClient;

    public List<Fruit> list(){
        List<Fruit> list = new ArrayList<>();
        MongoCursor<Fruit> cursor = getCollection().find().iterator();

        try {
            while (cursor.hasNext()) {
                list.add(cursor.next());
            }
        } finally {
            cursor.close();
        }
        return list;
    }

    public void add(Fruit fruit){
        getCollection().insertOne(fruit);
    }

    private MongoCollection<Fruit> getCollection(){
        return mongoClient.getDatabase("fruit").getCollection("fruit", Fruit.class);
    }
}

The POJO Codec

The POJO Codec provides a set of annotations that enable the customization of the way a POJO is mapped to a MongoDB collection and this codec is initialized automatically by Quarkus

One of these annotations is the @BsonDiscriminator annotation that allows to storage multiple Java types in a single MongoDB collection by adding a discriminator field inside the document. It can be useful when working with abstract types or interfaces.

Quarkus will automatically register all the classes annotated with @BsonDiscriminator with the POJO codec.

The POJO Codec have enhanced generic support via PropertyCodecProvider, Quarkus will automatically register any PropertyCodecProvider with the POJO Codec (these classes are automatically made CDI beans of @Singleton scope). When building native executables and using generic types, you might need to register the type arguments for reflection.

Simplifying MongoDB with Panache

The MongoDB with Panache extension facilitates the usage of MongoDB by providing active record style entities (and repositories) like you have in Hibernate ORM with Panache and focuses on making your entities trivial and fun to write in Quarkus.

Schema migration with Liquibase

The Liquibase MongoDB extension facilitates the initialization of a MongoDB database including indices and initial data. It implements the same schema migration facilities that Liquibase offers for SQL databases.

Connection Health Check

If you are using the quarkus-smallrye-health extension, quarkus-mongodb-client will automatically add a readiness health check to validate the connection to the cluster.

So when you access the /q/health/ready endpoint of your application you will have information about the connection validation status.

This behavior can be disabled by setting the quarkus.mongodb.health.enabled property to false in your application.properties.

Metrics

If you are using the quarkus-micrometer or quarkus-smallrye-metrics extension, quarkus-mongodb-client can provide metrics about the connection pools. This behavior must first be enabled by setting the quarkus.mongodb.metrics.enabled property to true in your application.properties.

So when you access the /q/metrics endpoint of your application you will have information about the connection pool status. When using SmallRye Metrics, connection pool metrics will be available under the vendor scope.

Tracing

If you are using the quarkus-smallrye-opentracing extension, quarkus-mongodb-client can register traces about the commands executed. This behavior must be enabled by setting the quarkus.mongodb.tracing.enabled property to true in your application.properties and adding the dependency io.opentracing.contrib:opentracing-mongo-common to your pom.xml (for more info read the OpenTracing - MongoDB client section).

Read the OpenTracing guide, for how to configure OpenTracing and how to use the Jaeger tracer.

Testing helpers

Dev Services for MongoDB is your best option to start a MongoDB database for your unit tests.

But if you can’t use it, you can start a MongoDB database using one of the two QuarkusTestResourceLifecycleManager that Quarkus provides. They rely on Flapdoodle embedded MongoDB.

  • io.quarkus.test.mongodb.MongoTestResource will start a single instance on port 27017.

  • io.quarkus.test.mongodb.MongoReplicaSetTestResource will start a replicaset with two instances, one on port 27017 and the other on port 27018.

To use them, you need to add the io.quarkus:quarkus-test-mongodb dependency to your pom.xml.

For more information about the usage of a QuarkusTestResourceLifecycleManager please read Quarkus test resource.

To set the desired port MongoDB will listen to when it is launched, the following code should be used:

@QuarkusTestResource(value = MongoTestResource.class, initArgs = @ResourceArg(name = MongoTestResource.PORT, value = "27017"))

To set the desired MongoDB version that will be launched, the following code should be used:

@QuarkusTestResource(value = MongoTestResource.class, initArgs = @ResourceArg(name = MongoTestResource.VERSION, value = "V5_0"))

The string value used can be any of one of the de.flapdoodle.embed.mongo.distribution.Version or de.flapdoodle.embed.mongo.distribution.Version.Main enums. If no version is specified, Version.Main.V4_0 is used by default.

The legacy client

We don’t include the legacy MongoDB client by default. It contains the now retired MongoDB Java API (DB, DBCollection,…​ ) and the com.mongodb.MongoClient that is now superseded by com.mongodb.client.MongoClient.

If you want to use the legacy API, you need to add the following dependency to your build file:

pom.xml
<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver-legacy</artifactId>
</dependency>
build.gradle
implementation("org.mongodb:mongodb-driver-legacy")

Building a native executable

You can use the MongoDB client in a native executable.

If you want to use SSL/TLS encryption, you need to add these properties in your application.properties:

quarkus.mongodb.tls=true
quarkus.mongodb.tls-insecure=true # only if TLS certificate cannot be validated

You can then build a native executable with the usual command:

CLI
quarkus build --native
Maven
./mvnw install -Dnative
Gradle
./gradlew build -Dquarkus.package.type=native

Running it is as simple as executing ./target/mongodb-quickstart-1.0.0-SNAPSHOT-runner.

You can then point your browser to http://localhost:8080/fruits.html and use your application.

Currently, Quarkus doesn’t support Client-Side Field Level Encryption in native mode.

If you encounter the following error when running your application in native mode:
Failed to encode 'MyObject'. Encoding 'myVariable' errored with: Can’t find a codec for class org.acme.MyVariable.
This means that the org.acme.MyVariable class is not known to GraalVM, the remedy is to add the @RegisterForReflection annotation to your MyVariable class. More details about the @RegisterForReflection annotation can be found on the native application tips page.

Using mongo+srv:// urls

mongo+srv:// urls are supported out of the box in JVM mode. However, in native, the default DNS resolver, provided by the MongoDB client, uses JNDI and does not work in native mode.

If you need to use mongo+srv:// in native mode, you can configure an alternative DNS resolver. This feature is experimental and may introduce a difference between JVM applications and native applications.

To enable the alternative DNS resolver, use:

quarkus.mongodb.native.dns.use-vertx-dns-resolver=true

As indicated in the property name, it uses Vert.x to retrieve the DNS records. By default, it tries to read the first nameserver from /etc/resolv.conf, if this file exists. You can also configure your DNS server:

quarkus.mongodb.native.dns.use-vertx-dns-resolver=true
quarkus.mongodb.native.dns.server-host=10.0.0.1
quarkus.mongodb.native.dns.server-port=53 # 53 is the default port

Also, you can configure the lookup timeout using:

quarkus.mongodb.native.dns.use-vertx-dns-resolver=true
quarkus.mongodb.native.dns.lookup-timeout=10s # the default is 5s

Configuration Reference

Configuration property fixed at build time - All other configuration properties are overridable at runtime

Configuration property

Type

Default

Whether a health check is published in case the smallrye-health extension is present.

Environment variable: QUARKUS_MONGODB_HEALTH_ENABLED

boolean

true

Whether metrics are published in case a metrics extension is present.

Environment variable: QUARKUS_MONGODB_METRICS_ENABLED

boolean

false

Whether tracing spans of driver commands are sent in case the smallrye-opentracing extension is present.

Environment variable: QUARKUS_MONGODB_TRACING_ENABLED

boolean

false

If set to true, the default clients will always be created even if there are no injection points that use them

Environment variable: QUARKUS_MONGODB_FORCE_DEFAULT_CLIENTS

boolean

false

If DevServices has been explicitly enabled or disabled. DevServices is generally enabled by default, unless there is an existing configuration present. When DevServices is enabled Quarkus will attempt to automatically configure and start a database when running in Dev or Test mode.

Environment variable: QUARKUS_MONGODB_DEVSERVICES_ENABLED

boolean

The container image name to use, for container based DevServices providers.

Environment variable: QUARKUS_MONGODB_DEVSERVICES_IMAGE_NAME

string

Optional fixed port the dev service will listen to. If not defined, the port will be chosen randomly.

Environment variable: QUARKUS_MONGODB_DEVSERVICES_PORT

int

Configures the connection string. The format is: mongodb://[username:password@]host1[:port1][,host2[:port2],…​[,hostN[:portN]]][/[database.collection][?options]] mongodb:// is a required prefix to identify that this is a string in the standard connection format. username:password@ are optional. If given, the driver will attempt to log in to a database after connecting to a database server. For some authentication mechanisms, only the username is specified and the password is not, in which case the ":" after the username is left off as well. host1 is the only required part of the connection string. It identifies a server address to connect to. :portX is optional and defaults to :27017 if not provided. /database is the name of the database to log in to and thus is only relevant if the username:password@ syntax is used. If not specified the admin database will be used by default. ?options are connection options. Note that if database is absent there is still a / required between the last host and the ? introducing the options. Options are name=value pairs and the pairs are separated by "&". An alternative format, using the mongodb+srv protocol, is: mongodb+srv://[username:password@]host[/[database][?options]] - mongodb+srv:// is a required prefix for this format. - username:password@ are optional. If given, the driver will attempt to login to a database after connecting to a database server. For some authentication mechanisms, only the username is specified and the password is not, in which case the ":" after the username is left off as well - host is the only required part of the URI. It identifies a single host name for which SRV records are looked up from a Domain Name Server after prefixing the host name with "_mongodb._tcp". The host/port for each SRV record becomes the seed list used to connect, as if each one were provided as host/port pair in a URI using the normal mongodb protocol. - /database is the name of the database to login to and thus is only relevant if the username:password@ syntax is used. If not specified the "admin" database will be used by default. - ?options are connection options. Note that if database is absent there is still a / required between the last host and the ? introducing the options. Options are name=value pairs and the pairs are separated by "&". Additionally with the mongodb+srv protocol, TXT records are looked up from a Domain Name Server for the given host, and the text value of each one is prepended to any options on the URI itself. Because the last specified value for any option wins, that means that options provided on the URI will override any that are provided via TXT records.

Environment variable: QUARKUS_MONGODB_CONNECTION_STRING

string

Configures the MongoDB server addressed (one if single mode). The addresses are passed as host:port.

Environment variable: QUARKUS_MONGODB_HOSTS

list of string

127.0.0.1:27017

Configure the database name.

Environment variable: QUARKUS_MONGODB_DATABASE

string

Configures the application name.

Environment variable: QUARKUS_MONGODB_APPLICATION_NAME

string

Configures the maximum number of connections in the connection pool.

Environment variable: QUARKUS_MONGODB_MAX_POOL_SIZE

int

Configures the minimum number of connections in the connection pool.

Environment variable: QUARKUS_MONGODB_MIN_POOL_SIZE

int

Maximum idle time of a pooled connection. A connection that exceeds this limit will be closed.

Environment variable: QUARKUS_MONGODB_MAX_CONNECTION_IDLE_TIME

Duration

Maximum lifetime of a pooled connection. A connection that exceeds this limit will be closed.

Environment variable: QUARKUS_MONGODB_MAX_CONNECTION_LIFE_TIME

Duration

Configures the time period between runs of the maintenance job.

Environment variable: QUARKUS_MONGODB_MAINTENANCE_FREQUENCY

Duration

Configures period of time to wait before running the first maintenance job on the connection pool.

Environment variable: QUARKUS_MONGODB_MAINTENANCE_INITIAL_DELAY

Duration

How long a connection can take to be opened before timing out.

Environment variable: QUARKUS_MONGODB_CONNECT_TIMEOUT

Duration

How long a socket read can take before timing out.

Environment variable: QUARKUS_MONGODB_READ_TIMEOUT

Duration

If connecting with TLS, this option enables insecure TLS connections.

Environment variable: QUARKUS_MONGODB_TLS_INSECURE

boolean

false

Whether to connect using TLS.

Environment variable: QUARKUS_MONGODB_TLS

boolean

false

Implies that the hosts given are a seed list, and the driver will attempt to find all members of the set.

Environment variable: QUARKUS_MONGODB_REPLICA_SET_NAME

string

How long the driver will wait for server selection to succeed before throwing an exception.

Environment variable: QUARKUS_MONGODB_SERVER_SELECTION_TIMEOUT

Duration

When choosing among multiple MongoDB servers to send a request, the driver will only send that request to a server whose ping time is less than or equal to the server with the fastest ping time plus the local threshold.

Environment variable: QUARKUS_MONGODB_LOCAL_THRESHOLD

Duration

The frequency that the driver will attempt to determine the current state of each server in the cluster.

Environment variable: QUARKUS_MONGODB_HEARTBEAT_FREQUENCY

Duration

Configures the read concern. Supported values are: local|majority|linearizable|snapshot|available

Environment variable: QUARKUS_MONGODB_READ_CONCERN

string

Configures the read preferences. Supported values are: primary|primaryPreferred|secondary|secondaryPreferred|nearest

Environment variable: QUARKUS_MONGODB_READ_PREFERENCE

string

The database used during the readiness health checks

Environment variable: QUARKUS_MONGODB_HEALTH_DATABASE

string

admin

This property configures the DNS server. If the server is not set, it tries to read the first nameserver from /etc /resolv.conf (if the file exists), otherwise fallback to the default.

Environment variable: QUARKUS_MONGODB_DNS_SERVER_HOST

string

This property configures the DNS server port.

Environment variable: QUARKUS_MONGODB_DNS_SERVER_PORT

int

53

If native.dns.use-vertx-dns-resolver is set to true, this property configures the DNS lookup timeout duration.

Environment variable: QUARKUS_MONGODB_DNS_LOOKUP_TIMEOUT

Duration

5S

This property enables the logging ot the DNS lookup. It can be useful to understand why the lookup fails.

Environment variable: QUARKUS_MONGODB_DNS_LOG_ACTIVITY

boolean

false

Generic properties that are added to the connection URL.

Environment variable: QUARKUS_MONGODB_DEVSERVICES_PROPERTIES

Map<String,String>

Configures the connection string. The format is: mongodb://[username:password@]host1[:port1][,host2[:port2],…​[,hostN[:portN]]][/[database.collection][?options]] mongodb:// is a required prefix to identify that this is a string in the standard connection format. username:password@ are optional. If given, the driver will attempt to log in to a database after connecting to a database server. For some authentication mechanisms, only the username is specified and the password is not, in which case the ":" after the username is left off as well. host1 is the only required part of the connection string. It identifies a server address to connect to. :portX is optional and defaults to :27017 if not provided. /database is the name of the database to log in to and thus is only relevant if the username:password@ syntax is used. If not specified the admin database will be used by default. ?options are connection options. Note that if database is absent there is still a / required between the last host and the ? introducing the options. Options are name=value pairs and the pairs are separated by "&". An alternative format, using the mongodb+srv protocol, is: mongodb+srv://[username:password@]host[/[database][?options]] - mongodb+srv:// is a required prefix for this format. - username:password@ are optional. If given, the driver will attempt to login to a database after connecting to a database server. For some authentication mechanisms, only the username is specified and the password is not, in which case the ":" after the username is left off as well - host is the only required part of the URI. It identifies a single host name for which SRV records are looked up from a Domain Name Server after prefixing the host name with "_mongodb._tcp". The host/port for each SRV record becomes the seed list used to connect, as if each one were provided as host/port pair in a URI using the normal mongodb protocol. - /database is the name of the database to login to and thus is only relevant if the username:password@ syntax is used. If not specified the "admin" database will be used by default. - ?options are connection options. Note that if database is absent there is still a / required between the last host and the ? introducing the options. Options are name=value pairs and the pairs are separated by "&". Additionally with the mongodb+srv protocol, TXT records are looked up from a Domain Name Server for the given host, and the text value of each one is prepended to any options on the URI itself. Because the last specified value for any option wins, that means that options provided on the URI will override any that are provided via TXT records.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__CONNECTION_STRING

string

Configures the MongoDB server addressed (one if single mode). The addresses are passed as host:port.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__HOSTS

list of string

127.0.0.1:27017

Configure the database name.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__DATABASE

string

Configures the application name.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__APPLICATION_NAME

string

Configures the maximum number of connections in the connection pool.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__MAX_POOL_SIZE

int

Configures the minimum number of connections in the connection pool.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__MIN_POOL_SIZE

int

Maximum idle time of a pooled connection. A connection that exceeds this limit will be closed.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__MAX_CONNECTION_IDLE_TIME

Duration

Maximum lifetime of a pooled connection. A connection that exceeds this limit will be closed.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__MAX_CONNECTION_LIFE_TIME

Duration

Configures the time period between runs of the maintenance job.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__MAINTENANCE_FREQUENCY

Duration

Configures period of time to wait before running the first maintenance job on the connection pool.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__MAINTENANCE_INITIAL_DELAY

Duration

How long a connection can take to be opened before timing out.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__CONNECT_TIMEOUT

Duration

How long a socket read can take before timing out.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__READ_TIMEOUT

Duration

If connecting with TLS, this option enables insecure TLS connections.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__TLS_INSECURE

boolean

false

Whether to connect using TLS.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__TLS

boolean

false

Implies that the hosts given are a seed list, and the driver will attempt to find all members of the set.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__REPLICA_SET_NAME

string

How long the driver will wait for server selection to succeed before throwing an exception.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__SERVER_SELECTION_TIMEOUT

Duration

When choosing among multiple MongoDB servers to send a request, the driver will only send that request to a server whose ping time is less than or equal to the server with the fastest ping time plus the local threshold.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__LOCAL_THRESHOLD

Duration

The frequency that the driver will attempt to determine the current state of each server in the cluster.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__HEARTBEAT_FREQUENCY

Duration

Configures the read concern. Supported values are: local|majority|linearizable|snapshot|available

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__READ_CONCERN

string

Configures the read preferences. Supported values are: primary|primaryPreferred|secondary|secondaryPreferred|nearest

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__READ_PREFERENCE

string

The database used during the readiness health checks

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__HEALTH_DATABASE

string

admin

Write concern

Type

Default

Configures the safety. If set to true: the driver ensures that all writes are acknowledged by the MongoDB server, or else throws an exception. (see also w and wtimeoutMS). If set fo - false: the driver does not ensure that all writes are acknowledged by the MongoDB server.

Environment variable: QUARKUS_MONGODB_WRITE_CONCERN_SAFE

boolean

true

Configures the journal writing aspect. If set to true: the driver waits for the server to group commit to the journal file on disk. If set to false: the driver does not wait for the server to group commit to the journal file on disk.

Environment variable: QUARKUS_MONGODB_WRITE_CONCERN_JOURNAL

boolean

true

When set, the driver adds w: wValue to all write commands. It requires safe to be true. The value is typically a number, but can also be the majority string.

Environment variable: QUARKUS_MONGODB_WRITE_CONCERN_W

string

If set to true, the driver will retry supported write operations if they fail due to a network error.

Environment variable: QUARKUS_MONGODB_WRITE_CONCERN_RETRY_WRITES

boolean

false

When set, the driver adds wtimeout : ms to all write commands. It requires safe to be true.

Environment variable: QUARKUS_MONGODB_WRITE_CONCERN_W_TIMEOUT

Duration

Configures the safety. If set to true: the driver ensures that all writes are acknowledged by the MongoDB server, or else throws an exception. (see also w and wtimeoutMS). If set fo - false: the driver does not ensure that all writes are acknowledged by the MongoDB server.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__WRITE_CONCERN_SAFE

boolean

true

Configures the journal writing aspect. If set to true: the driver waits for the server to group commit to the journal file on disk. If set to false: the driver does not wait for the server to group commit to the journal file on disk.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__WRITE_CONCERN_JOURNAL

boolean

true

When set, the driver adds w: wValue to all write commands. It requires safe to be true. The value is typically a number, but can also be the majority string.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__WRITE_CONCERN_W

string

If set to true, the driver will retry supported write operations if they fail due to a network error.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__WRITE_CONCERN_RETRY_WRITES

boolean

false

When set, the driver adds wtimeout : ms to all write commands. It requires safe to be true.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__WRITE_CONCERN_W_TIMEOUT

Duration

Credentials and authentication mechanism

Type

Default

Configures the username.

Environment variable: QUARKUS_MONGODB_CREDENTIALS_USERNAME

string

Configures the password.

Environment variable: QUARKUS_MONGODB_CREDENTIALS_PASSWORD

string

Configures the authentication mechanism to use if a credential was supplied. The default is unspecified, in which case the client will pick the most secure mechanism available based on the sever version. For the GSSAPI and MONGODB-X509 mechanisms, no password is accepted, only the username. Supported values: null or GSSAPI|PLAIN|MONGODB-X509|SCRAM_SHA_1|SCRAM_SHA_256|MONGODB_AWS

Environment variable: QUARKUS_MONGODB_CREDENTIALS_AUTH_MECHANISM

string

Configures the source of the authentication credentials. This is typically the database that the credentials have been created. The value defaults to the database specified in the path portion of the connection string or in the 'database' configuration property. If the database is specified in neither place, the default value is admin. This option is only respected when using the MONGO-CR mechanism (the default).

Environment variable: QUARKUS_MONGODB_CREDENTIALS_AUTH_SOURCE

string

Allows passing authentication mechanism properties.

Environment variable: QUARKUS_MONGODB_CREDENTIALS_AUTH_MECHANISM_PROPERTIES

Map<String,String>

Configures the username.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__CREDENTIALS_USERNAME

string

Configures the password.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__CREDENTIALS_PASSWORD

string

Configures the authentication mechanism to use if a credential was supplied. The default is unspecified, in which case the client will pick the most secure mechanism available based on the sever version. For the GSSAPI and MONGODB-X509 mechanisms, no password is accepted, only the username. Supported values: null or GSSAPI|PLAIN|MONGODB-X509|SCRAM_SHA_1|SCRAM_SHA_256|MONGODB_AWS

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__CREDENTIALS_AUTH_MECHANISM

string

Configures the source of the authentication credentials. This is typically the database that the credentials have been created. The value defaults to the database specified in the path portion of the connection string or in the 'database' configuration property. If the database is specified in neither place, the default value is admin. This option is only respected when using the MONGO-CR mechanism (the default).

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__CREDENTIALS_AUTH_SOURCE

string

Allows passing authentication mechanism properties.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__CREDENTIALS_AUTH_MECHANISM_PROPERTIES

Map<String,String>

About the Duration format

The format for durations uses the standard java.time.Duration format. You can learn more about it in the Duration#parse() javadoc.

You can also provide duration values starting with a number. In this case, if the value consists only of a number, the converter treats the value as seconds. Otherwise, PT is implicitly prepended to the value to obtain a standard java.time.Duration format.