As modern applications increasingly demand flexibility and scalability, the combination of Spring Boot and MongoDB has emerged as a great solution for developers. Spring Boot, a popular framework in the Java ecosystem, streamlines the process of building production-ready applications, while MongoDB, a leading NoSQL database, offers a schema-less data model that can easily accommodate varying data structures. Together, these technologies enable developers to create robust, high-performance applications with ease. In this blog, we'll be going through the basics of creating a back end service with Spring Boot and MongoDB, walk through essential setup steps, and provide a technical example to help you understand how both of these technologies work together.
What you'll need
The contents of this blog work best in a Linux environment. You'll also need to have these technologies installed on your computer.
- Docker-compose (required)
- Maven (required)
- Java (required)
- IntelliJ IDEA (optional) - for implementing your code. You can use vscode or your preferred application.
Creating the spring boot application
Open spring initialzr on your browser (https://start.spring.io/) and tweak the project with the following configurations:
- Project: MAVEN
- Language: Java
- Springboot version: 3.3.3
- Project metadata:
- Packaging: JAR
- Java version: 21
- Dependencies:
spring-boot-starter-data-mongodb
spring-boot-starter-web
lombok
Generate the project, and it will be automatically downloaded to your computer. Navigate to the ~/Downloads folder and extract the contents from the zip file.
Open the project with IntelliJ IDEA. The IDE will cache and build the Maven dependencies of the application.
Try to run the Spring Boot application with the command mvn spring-boot:run
. Don't worry if the application does not work after you run it; this is expected, as the application has no MongoDB database to connect to yet.
com.mongodb.MongoSocketOpenException: Exception opening socket
at com.mongodb.internal.connection.SocketStream.lambda$open$0(SocketStream.java:86) ~[mongodb-driver-core-5.0.1.jar:na]
at java.base/java.util.Optional.orElseThrow(Optional.java:403) ~[na:na]
at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:86) ~[mongodb-driver-core-5.0.1.jar:na]
at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:201) ~[mongodb-driver-core-5.0.1.jar:na]
at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.lookupServerDescription(DefaultServerMonitor.java:193) ~[mongodb-driver-core-5.0.1.jar:na]
at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:153) ~[mongodb-driver-core-5.0.1.jar:na]
at java.base/java.lang.Thread.run(Thread.java:1583) ~[na:na]
Caused by: java.net.ConnectException: Connection refused
at java.base/sun.nio.ch.Net.pollConnect(Native Method) ~[na:na]
at java.base/sun.nio.ch.Net.pollConnectNow(Net.java:682) ~[na:na]
at java.base/sun.nio.ch.NioSocketImpl.timedFinishConnect(NioSocketImpl.java:542) ~[na:na]
at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:592) ~[na:na]
at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:327) ~[na:na]
at java.base/java.net.Socket.connect(Socket.java:751) ~[na:na]
at com.mongodb.internal.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:76) ~[mongodb-driver-core-5.0.1.jar:na]
at com.mongodb.internal.connection.SocketStream.initializeSocket(SocketStream.java:105) ~[mongodb-driver-core-5.0.1.jar:na]
at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:80) ~[mongodb-driver-core-5.0.1.jar:na]
... 4 common frames omitted
Setting up mongo and mongo-express
Using docker compose
Create a Docker Compose file in the root folder of the project. If you're on Linux, you can use the command touch docker-compose.yml
.
Paste this content into the Docker Compose file. I've added descriptions for each line of the code to explain what each line means:
services: # Defines the services to be run. `mongodb` will be the name of the service to run the actual database, while `mongo-express` will be the one to run the express application.
mongodb:
image: mongo:latest # Describes the image to be used when running the service. This is configured per service.
ports:
- "27017:27017" # Describes the port binding of the docker container with the virtual port of the host machine.
environment: # Values of environment variables are defined on this part of the config.
- MONGO_INITDB_ROOT_USERNAME=admin # The admin and password env variables must be followed otherwise mongo won't work properly.
- MONGO_INITDB_ROOT_PASSWORD=password
volumes:
- mongo-data:/data/db # We define a docker volume in here to house the data persistence for our mongodatabase. And then we bind the volume to the service.
mongo-express:
image: mongo-express:latest
restart: always # This tells docker to always restart the service-container when execution is stopped.
ports:
- "8081:8081"
environment:
- ME_CONFIG_MONGODB_ADMINUSERNAME=admin # The values for the mongodb credentials must match what is defined on the database service-container (above).
- ME_CONFIG_MONGODB_ADMINPASSWORD=password
- ME_CONFIG_MONGODB_SERVER=mongodb # Describe the server name of the database. In this case, it's the service-container that is running the mongodb.
depends_on:
- "mongodb" # This tells docker to not run `mongo-express` if `mongodb` has not started successfully.
volumes: # We define the volumes used by the services here.
mongo-data:
driver: local
Taking steps further
You can create a Makefile to streamline the commands for starting and running the applications. Create a new file and name it Makefile
, and then copy this content into the file:
.PHONY: start-db
start-db:
docker compose up # Executes docker compose up to run the database services (mongodb and express).
.PHONY: start-app
start-app:
mvn spring-boot:run # Uses maven and command to run the application.
Running the database service
You can use the Docker Compose command in your terminal, or if you have created a Makefile, you can use make start-db
to run the database-related services.
Thing to note: MongoDB might take a minute to fully load, which may cause the Express container to throw error messages because it cannot connect to the database. Just wait for a few minutes until you see these lines of code in your terminal:
mongo-express-1 | Mongo Express server listening at http://0.0.0.0:8081
mongo-express-1 | Server is open to allow connections from anyone (0.0.0.0)
mongo-express-1 | basicAuth credentials are "admin:pass", it is recommended you change this in your config.js!
âšī¸ The credentials for accessing the Mongo Express app are "admin:pass". This is okay since this is just a simple tutorial. However, in the real world, we need to implement a layer of security to keep our access and data safe.
Mongo express
Mongo Express is a web-based administrative interface designed for managing MongoDB databases. It provides a user-friendly dashboard that allows developers and database administrators to perform essential tasks such as creating and modifying databases, collections, and documents without needing to interact directly with the MongoDB shell. We'll be using the mongo express UI to interact with the mongodb database.
After running the database services, you can access the mongo express on your browser at http://localhost:8081/
.
Connecting to mongo database
Back in IntelliJ, rename the application.properties file to application.yml.
Paste this content into the application.yml file:
spring:
application:
name: springboot-and-mongodb
data:
mongodb:
authentication-database: admin
username: admin
password: password
database: simpleDB # need to manually create this db on mongo-express
port: 27017
host: localhost
auto-index-creation: true
server:
port: 8080
This configuration simply tells the Spring Boot application the information it needs to connect to the MongoDB database. We will be using the database simpleDB, which we will need to create manually later on.
This config also sets the application port to 8080
(the default for Spring Boot apps).
You can test the application to see if it can now connect to MongoDB. Remember, MongoDB takes time to load, so make sure that it's properly loaded before you run the Spring Boot service.
Conclusion
In this blog, we have gone through setting up the basic parts of building a backend service with Java Spring Boot and MongoDB. We created a new Spring Boot project, configured its dependencies and application settings, and implemented the configuration for running MongoDB and Mongo Express in a local environment using Docker. Leveraging Docker to run the database services eliminates the dependency problem of installing a MongoDB server on your local machine. This ensures that your database setup will run and be deployed on any Linux machine with the same configuration and ease.
In the next part, we'll discuss implementing basic CRUD operations with the Back End service that we have created, building on the progress we've made in this blog.
Top comments (0)