BlogAnnounced at MongoDB.local NYC 2024: A recap of all announcements and updatesLearn more >>
MongoDB Developer
Java
plus
Sign in to follow topics
MongoDB Developer Centerchevron-right
Developer Topicschevron-right
Languageschevron-right
Javachevron-right

Creating a REST API for CRUD Operations With Quarkus and MongoDB

Maxime Beugnet7 min read • Published Apr 17, 2024 • Updated Apr 17, 2024
QuarkusDockerMongoDBJava
Facebook Icontwitter iconlinkedin icon
Rate this quickstart
star-empty
star-empty
star-empty
star-empty
star-empty

What is Quarkus?

When we write a traditional Java application, our Java source code is compiled and transformed into Java bytecode. This bytecode can then be executed by a Java virtual machine (JVM) specific to the operating system you are running. This is why we can say that Java is a portable language. You compile once, and you can run it everywhere, as long as you have the right JVM on the right machine.
This is a great mechanism, but it comes at a cost. Starting a program is slow because the JVM and the entire context need to be loaded first before running anything. It's not memory-efficient because we need to load hundreds of classes that might not be used at all in the end as the classpath scanning only occurs after.
This was perfectly fine in the old monolithic realm, but this is totally unacceptable in the new world made of lambda functions, cloud, containers, and Kubernetes. In this context, a low memory footprint and a lightning-fast startup time are absolutely mandatory.
This is where Quarkus comes in. Quarkus is a Kubernetes-native Java framework tailored for GraalVM and HotSpot.
With Quarkus, you can build native binaries that can boot and send their first response in 0.042 seconds versus 9.5 seconds for a traditional Java application.
Quarkus startup time
In this tutorial, we are going to build a Quarkus application that can manage a persons collection in MongoDB. The goal is to perform four simple CRUD operations with a REST API using a native application.

Prerequisites

For this tutorial, you'll need:
If you don't want to code along and prefer to check out directly the final code:

How to set up Quarkus with MongoDB

TL;DR: Use this link and click on generate your application or clone the GitHub repository.
The easiest way to get your project up and running with Quarkus and all the dependencies you need is to use https://code.quarkus.io/.
Similar to Spring initializr, the Quarkus project starter website will help you select your dependencies and build your Maven or Gradle configuration file. Some dependencies will also include a starter code to assist you in your first steps.
For our project, we are going to need:
  • MongoDB client [quarkus-mongodb-client].
  • SmallRye OpenAPI [quarkus-smallrye-openapi].
  • REST [quarkus-rest].
  • REST Jackson [quarkus-rest-jackson].
Feel free to use the group and artifact of your choice. Make sure the Java version matches the version of your GraalVM version, and we are ready to go.
Download the zip file and unzip it in your favorite project folder. Once it's done, take some time to read the README.md file provided.
Finally, we need a MongoDB cluster. Two solutions:
  • Create a new cluster on MongoDB Atlas and retrieve the connection string, or
  • Create an ephemeral single-node replica set with Docker.
Either way, the next step is to set up your connection string in the application.properties file.

CRUD operations in Quarkus with MongoDB

Now that our Quarkus project is ready, we can start developing.
First, we can start the developer mode which includes live coding (automatic refresh) without the need to restart the program.
The developer mode comes with two handy features:
Feel free to take some time to explore both these UIs and see the capabilities they offer.
Also, as your service is now running, you should be able to receive your first HTTP communication. Open a new terminal and execute the following query:
Note: If you cloned the repo, then it’s /api/hello. We are changing this below in a minute.
Result:
This works because your project currently contains a single class GreetingResource.java with the following code.

PersonEntity

"Hello from Quarkus REST" is nice, but it's not our goal! We want to manipulate data from a persons collection in MongoDB.
Let's create a classic PersonEntity.java POJO class. I created it in the default com.mongodb package which is my group from earlier. Feel free to change it.
We now have a class to map our MongoDB documents to using Jackson.

PersonRepository

Now that we have a PersonEntity, we can create a PersonRepository template, ready to welcome our CRUD queries.
Create a PersonRepository.java class next to the PersonEntity.java one.

PersonResource

We are now almost ready to create our first CRUD method. Let's update the default GreetingResource.java class to match our goal.
  1. Rename the file GreetingResource.java to PersonResource.java.
  2. In the test folder, also rename the default test files to PersonResourceIT.java and PersonResourceTest.java.
  3. Update PersonResource.java like this:
Note that with the @Path("/api") annotation, the URL of our /hello service is now /api/hello.
As a consequence, update PersonResourceTest.java so our test keeps working.

Create a person

All the code blocks are now in place. We can create our first route to be able to create a new person.
In the repository, add the following method that inserts a PersonEntity and returns the inserted document's ObjectId in String format.
In the resource file, we can create the corresponding route:
Without restarting the project (remember the dev mode?), you should be able to test this route.
This should return the ObjectId of the new person document.
If you connect to the MongoDB instance with mongosh, you can confirm that the document made it:

Read persons

Now, we can read all the persons in the database, for example.
In the repository, add:
In the resource, add:
Now, we can retrieve all the persons in our database:
This returns a list of persons:

Update person

It's John Doe's anniversary! Let's increment his age by one.
In the repository, add:
In the resource, add:
Time to test this party:
This returns 1 which is the number of modified document(s). If the provided ObjectId doesn't match a person's id, then it returns 0 and MongoDB doesn't perform any update.

Delete person

Finally, it's time to delete John Doe...
In the repository, add:
In the resource, add:
Let's test:
Again, it returns 1 which is the number of deleted document(s).
Now that we have a working Quarkus application with a MongoDB CRUD service, it's time to experience the full power of Quarkus.

Quarkus native build

Quit the developer mode by simply hitting the q key in the relevant terminal.
It's time to build the native executable that we can use in production with GraalVM and experience the insanely fast start-up time.
Use this command line to build directly with your local GraalVM and other dependencies.
Or use the Docker image that contains everything you need:
The final result is a native application, ready to be launched, in your target folder.
On my laptop, it starts in just 0.019s! Remember how much time Spring Boot needs to start an application and respond to queries for the first time?!
You can read more about how Quarkus makes this miracle a reality in the container first documentation.

Conclusion

In this tutorial, we've explored how Quarkus and MongoDB can team up to create a lightning-fast RESTful API with CRUD capabilities.
Now equipped with these insights, you're ready to build blazing-fast APIs with Quarkus, GraalVM, and MongoDB. Dive into the provided GitHub repository for more details.
If you have questions, please head to our Developer Community website where the MongoDB engineers and the MongoDB community will help you build your next big idea with MongoDB.

Facebook Icontwitter iconlinkedin icon
Rate this quickstart
star-empty
star-empty
star-empty
star-empty
star-empty
Related
Tutorial

Secure your API with Spring Data MongoDB and Microsoft EntraID


Apr 02, 2024 | 8 min read
Article

How to Build a Search Service in Java


Apr 23, 2024 | 11 min read
Tutorial

Serverless Development with AWS Lambda and MongoDB Atlas Using Java


Jul 20, 2023 | 6 min read
Quickstart

Getting Started with MongoDB and Java - CRUD Operations Tutorial


Mar 01, 2024 | 24 min read
Table of Contents