Quarkus - 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:

  • less than 15 minutes

  • an IDE

  • JDK 1.8+ installed with JAVA_HOME configured appropriately

  • Apache Maven 3.6.2+

  • 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](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:

  1. mvn io.quarkus:quarkus-maven-plugin:1.7.6.Final:create \
  2. -DprojectGroupId=org.acme \
  3. -DprojectArtifactId=mongodb-quickstart \
  4. -DclassName="org.acme.mongodb.FruitResource" \
  5. -Dpath="/fruits" \
  6. -Dextensions="resteasy-jsonb,mongodb-client,resteasy-mutiny,context-propagation"
  7. cd mongodb-quickstart

This command generates a Maven structure importing the RESTEasy/JAX-RS, JSON-B, Mutiny, Context Propagation and MongoDB Client extensions. After this, the quarkus-mongodb-client extension has been added to your pom.xml.

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:

  1. ./mvnw quarkus:add-extension -Dextensions="mongodb-client"

This will add the following to your pom.xml:

  1. <dependency>
  2. <groupId>io.quarkus</groupId>
  3. <artifactId>quarkus-mongodb-client</artifactId>
  4. </dependency>

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:

  1. package org.acme.mongodb;
  2. import java.util.Objects;
  3. public class Fruit {
  4. private String name;
  5. private String description;
  6. private String id;
  7. public Fruit() {
  8. }
  9. public Fruit(String name, String description) {
  10. this.name = name;
  11. this.description = description;
  12. }
  13. public String getName() {
  14. return name;
  15. }
  16. public void setName(String name) {
  17. this.name = name;
  18. }
  19. public String getDescription() {
  20. return description;
  21. }
  22. public void setDescription(String description) {
  23. this.description = description;
  24. }
  25. @Override
  26. public boolean equals(Object obj) {
  27. if (!(obj instanceof Fruit)) {
  28. return false;
  29. }
  30. Fruit other = (Fruit) obj;
  31. return Objects.equals(other.name, this.name);
  32. }
  33. @Override
  34. public int hashCode() {
  35. return Objects.hash(this.name);
  36. }
  37. public void setId(String id) {
  38. this.id = id;
  39. }
  40. public String getId() {
  41. return id;
  42. }
  43. }

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.

  1. package org.acme.mongodb;
  2. import com.mongodb.client.MongoClient;
  3. import com.mongodb.client.MongoCollection;
  4. import com.mongodb.client.MongoCursor;
  5. import org.bson.Document;
  6. import javax.enterprise.context.ApplicationScoped;
  7. import javax.inject.Inject;
  8. import java.util.ArrayList;
  9. import java.util.List;
  10. @ApplicationScoped
  11. public class FruitService {
  12. @Inject MongoClient mongoClient;
  13. public List<Fruit> list(){
  14. List<Fruit> list = new ArrayList<>();
  15. MongoCursor<Document> cursor = getCollection().find().iterator();
  16. try {
  17. while (cursor.hasNext()) {
  18. Document document = cursor.next();
  19. Fruit fruit = new Fruit();
  20. fruit.setName(document.getString("name"));
  21. fruit.setDescription(document.getString("description"));
  22. list.add(fruit);
  23. }
  24. } finally {
  25. cursor.close();
  26. }
  27. return list;
  28. }
  29. public void add(Fruit fruit){
  30. Document document = new Document()
  31. .append("name", fruit.getName())
  32. .append("description", fruit.getDescription());
  33. getCollection().insertOne(document);
  34. }
  35. private MongoCollection getCollection(){
  36. return mongoClient.getDatabase("fruit").getCollection("fruit");
  37. }
  38. }

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

  1. @Path("/fruits")
  2. @Produces(MediaType.APPLICATION_JSON)
  3. @Consumes(MediaType.APPLICATION_JSON)
  4. public class FruitResource {
  5. @Inject FruitService fruitService;
  6. @GET
  7. public List<Fruit> list() {
  8. return fruitService.list();
  9. }
  10. @POST
  11. public List<Fruit> add(Fruit fruit) {
  12. fruitService.add(fruit);
  13. return list();
  14. }
  15. }

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:

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

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

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

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

Multiple MongoDB Clients

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

  1. quarkus.mongodb.connection-string = mongodb://login:pass@mongo1:27017/database
  2. quarkus.mongodb.users.connection-string = mongodb://mongo2:27017/userdb
  3. 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 (like 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.runtime.MongoClientName qualifier. Using the above properties to configure three different clients, you can also inject each one as follows:

  1. @Inject
  2. MongoClient defaultMongoClient;
  3. @Inject
  4. @MongoClientName("users")
  5. MongoClient mongoClient1;
  6. @Inject
  7. @MongoClientName("inventory")
  8. 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:

  1. docker run -ti --rm -p 27017:27017 mongo:4.0

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 ./mvnw compile quarkus:dev

  • open a browser to [http://localhost:8080/fruits.html](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.

Deprecation

The io.quarkus.mongodb.ReactiveMongoClient client is deprecated and will be removed in the future. It is recommended to switch to the io.quarkus.mongodb.reactive.ReactiveMongoClient client providing the Mutiny API.

Mutiny

The MongoDB reactive client uses Mutiny reactive types, if you’re not familiar with them, read the Getting Started with Reactive guide first.

  1. package org.acme.mongodb;
  2. import io.quarkus.mongodb.reactive.ReactiveMongoClient;
  3. import io.quarkus.mongodb.reactive.ReactiveMongoCollection;
  4. import io.smallrye.mutiny.Uni;
  5. import org.bson.Document;
  6. import javax.enterprise.context.ApplicationScoped;
  7. import javax.inject.Inject;
  8. import java.util.List;
  9. @ApplicationScoped
  10. public class ReactiveFruitService {
  11. @Inject
  12. ReactiveMongoClient mongoClient;
  13. public Uni<List<Fruit>> list() {
  14. return getCollection().find()
  15. .map(doc -> {
  16. Fruit fruit = new Fruit();
  17. fruit.setName(doc.getString("name"));
  18. fruit.setDescription(doc.getString("description"));
  19. return fruit;
  20. }).collectItems().asList();
  21. }
  22. public Uni<Void> add(Fruit fruit) {
  23. Document document = new Document()
  24. .append("name", fruit.getName())
  25. .append("description", fruit.getDescription());
  26. return getCollection().insertOne(document)
  27. .onItem().ignore().andContinueWithNull();
  28. }
  29. private ReactiveMongoCollection<Document> getCollection() {
  30. return mongoClient.getDatabase("fruit").getCollection("fruit");
  31. }
  32. }
  1. package org.acme.mongodb;
  2. import io.smallrye.mutiny.Uni;
  3. import java.util.List;
  4. import javax.inject.Inject;
  5. import javax.ws.rs.Path;
  6. import javax.ws.rs.Produces;
  7. import javax.ws.rs.Consumes;
  8. import javax.ws.rs.GET;
  9. import javax.ws.rs.POST;
  10. import javax.ws.rs.core.MediaType;
  11. @Path("/reactive_fruits")
  12. @Produces(MediaType.APPLICATION_JSON)
  13. @Consumes(MediaType.APPLICATION_JSON)
  14. public class ReactiveFruitResource {
  15. @Inject
  16. ReactiveFruitService fruitService;
  17. @GET
  18. public Uni<List<Fruit>> list() {
  19. return fruitService.list();
  20. }
  21. @POST
  22. public Uni<List<Fruit>> add(Fruit fruit) {
  23. return fruitService.add(fruit)
  24. .onItem().ignore().andSwitchTo(this::list);
  25. }
  26. }

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://mongodb.github.io/mongo-java-driver/3.10/bson/codecs.

  1. package org.acme.mongodb.codec;
  2. import com.mongodb.MongoClientSettings;
  3. import org.acme.mongodb.Fruit;
  4. import org.bson.Document;
  5. import org.bson.BsonWriter;
  6. import org.bson.BsonValue;
  7. import org.bson.BsonReader;
  8. import org.bson.BsonString;
  9. import org.bson.codecs.Codec;
  10. import org.bson.codecs.CollectibleCodec;
  11. import org.bson.codecs.DecoderContext;
  12. import org.bson.codecs.EncoderContext;
  13. import java.util.UUID;
  14. public class FruitCodec implements CollectibleCodec<Fruit> {
  15. private final Codec<Document> documentCodec;
  16. public FruitCodec() {
  17. this.documentCodec = MongoClientSettings.getDefaultCodecRegistry().get(Document.class);
  18. }
  19. @Override
  20. public void encode(BsonWriter writer, Fruit fruit, EncoderContext encoderContext) {
  21. Document doc = new Document();
  22. doc.put("name", fruit.getName());
  23. doc.put("description", fruit.getDescription());
  24. documentCodec.encode(writer, doc, encoderContext);
  25. }
  26. @Override
  27. public Class<Fruit> getEncoderClass() {
  28. return Fruit.class;
  29. }
  30. @Override
  31. public Fruit generateIdIfAbsentFromDocument(Fruit document) {
  32. if (!documentHasId(document)) {
  33. document.setId(UUID.randomUUID().toString());
  34. }
  35. return document;
  36. }
  37. @Override
  38. public boolean documentHasId(Fruit document) {
  39. return document.getId() != null;
  40. }
  41. @Override
  42. public BsonValue getDocumentId(Fruit document) {
  43. return new BsonString(document.getId());
  44. }
  45. @Override
  46. public Fruit decode(BsonReader reader, DecoderContext decoderContext) {
  47. Document document = documentCodec.decode(reader, decoderContext);
  48. Fruit fruit = new Fruit();
  49. if (document.getString("id") != null) {
  50. fruit.setId(document.getString("id"));
  51. }
  52. fruit.setName(document.getString("name"));
  53. fruit.setDescription(document.getString("description"));
  54. return fruit;
  55. }
  56. }

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

  1. package org.acme.mongodb.codec;
  2. import org.acme.mongodb.Fruit;
  3. import org.bson.codecs.Codec;
  4. import org.bson.codecs.configuration.CodecProvider;
  5. import org.bson.codecs.configuration.CodecRegistry;
  6. public class FruitCodecProvider implements CodecProvider {
  7. @Override
  8. public <T> Codec<T> get(Class<T> clazz, CodecRegistry registry) {
  9. if (clazz == Fruit.class) {
  10. return (Codec<T>) new FruitCodec();
  11. }
  12. return null;
  13. }
  14. }

Quarkus takes care of registering the CodecProvider for you.

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.

  1. package org.acme.mongodb;
  2. import com.mongodb.client.MongoClient;
  3. import com.mongodb.client.MongoCollection;
  4. import com.mongodb.client.MongoCursor;
  5. import javax.enterprise.context.ApplicationScoped;
  6. import javax.inject.Inject;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9. @ApplicationScoped
  10. public class CodecFruitService {
  11. @Inject MongoClient mongoClient;
  12. public List<Fruit> list(){
  13. List<Fruit> list = new ArrayList<>();
  14. MongoCursor<Fruit> cursor = getCollection().find().iterator();
  15. try {
  16. while (cursor.hasNext()) {
  17. list.add(cursor.next());
  18. }
  19. } finally {
  20. cursor.close();
  21. }
  22. return list;
  23. }
  24. public void add(Fruit fruit){
  25. getCollection().insertOne(fruit);
  26. }
  27. private MongoCollection<Fruit> getCollection(){
  28. return mongoClient.getDatabase("fruit").getCollection("fruit", Fruit.class);
  29. }
  30. }

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.

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.

Connection Health Check

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

So when you access the /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-smallrye-metrics extension, quarkus-mongodb 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 /metrics endpoint of your application you will have information about the connection pool status in the vendor scope.

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 pom.xml:

  1. <dependency>
  2. <groupId>org.mongodb</groupId>
  3. <artifactId>mongodb-driver-legacy</artifactId>
  4. </dependency>

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:

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

You can then build a native executable with the usual command ./mvnw package -Pnative.

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

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

Currently, Quarkus doesn’t support the mongodb+srv protocol in native mode.

Client-Side Field Level Encryption is also not supported 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.

Conclusion

Accessing a MongoDB database from a MongoDB Client is easy with Quarkus as it provides configuration and native support for it.

Configuration Reference

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.