Spring Boot and MongoDB
In this tutorial we'll use Spring Boot to access data from a MongoDB Atlas cluster. To follow along you'll need to sign in to MongoDB Atlas.
FAQ
To make the connection between your Spring Boot app and MongoDB, you should have two things:Â
- Spring Data MongoDB configurations in the pom.xml or Gradle configurations files
- The connection string with the correct driver version and database configurations in an application.properties file
The MongoTemplate in Spring Boot allows you to perform operations like CRUD, aggregations, and queries with the MongoDB database from the application end.
Different annotations that are used in Spring Boot applications with MongoDB are:
- @Document: This marks the class as the MongoDB document and is generally used in the model class.
- @Id: This is to represent the MongoDB _id in the model class.
- @Query: This is used to define complex queries on the MongoDB repository class.
- @EnableMongoRepositories: This annotation is useful to enable the Spring Data repositories in the application.
To connect your Spring Boot application in the Gradle setup, you need to add the following to the grade.build file and then add the URI to the application.properties file.Â
plugins {
id 'java'
id 'org.springframework.boot' version '3.3.4'
id 'io.spring.dependency-management' version '1.1.6'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
java {
toolchain {
languageVersion = JavaLanguageVersion.of(23)
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}
tasks.named('test') {
useJUnitPlatform()
}
The Spring Boot framework is used to create production-ready web applications with default configurations. Developers need not write extensive code. Spring Boot significantly reduces the development time. It automatically adds commonly used libraries for web applications, such as:
- spring-webmvc.
- tomcat.
- validation-api.
Spring Boot also has embedded servlet container support. We can run Java programs as a standalone application by adding the spring-boot-starter-web dependency in pom.xml.
Whether you're just learning Spring Boot or a Spring expert, MongoDB has you covered. To find more Spring Boot tutorials, information on the underlying Spring framework, or sample applications using Spring, refer to the following: