MongoDB is a popular NoSQL database that stores data in JSON-like documents instead of traditional tables and rows. It is flexible and widely used in modern applications because it does not require a fixed schema. Spring Boot provides easy integration with MongoDB using Spring Data MongoDB, which simplifies database access and reduces boilerplate code.
- Supports dynamic schema, allowing easy modification of data structure without affecting existing data.
- Spring Boot enables quick setup and seamless integration with MongoDB using auto-configuration and starter dependencies.
Prerequisites
- Java 8 or higher
- MongoDB
- Any IDE such as IntelliJ IDEA, Eclipse IDE
Steps To Implements MongoDB with Spring Boot
Step 1: Create a Spring Boot Project
Create a new project using Spring Initializr.
Project Configuration
- Project: Maven
- Language: Java
- Spring Boot Version: Latest stable version
- Group: com.gfg
- Artifact: springBoot-MongoDB-SampleProject
- Packaging: Jar
- Java Version: 17 or higher
Add Dependencies:
Select the following dependencies:
- Spring Web
- Spring Data MongoDB
Download the project, extract it, and open it in your IDE.

Step 2: Project Structure
After creating the project, the folder structure will look like this:

As it is a maven project, let's start with adding dependencies viaÂ
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gfg</groupId>
<artifactId>springboot-mongodb-project</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-mongodb-project</name>
<description>Spring Boot MongoDB Project</description>
<!-- Spring Boot 3 (Latest Stable) -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.5</version>
<relativePath/>
</parent>
<!-- Java 17+ Required -->
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<!-- Spring Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MongoDB Integration -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<!-- Optional: Lombok (reduces boilerplate) -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- Optional: Validation (for @Valid) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- Optional: DevTools (auto restart during dev) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Testing -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!-- Spring Boot Plugin -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- Compiler Plugin (Java 17) -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>17</source>
<target>17</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
File to mention the connectivity with MongoDB database
Step 3: Add MongoDB Configuration
Open application.properties and configure the MongoDB connection.application.properties
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=geeksforgeeks
This configuration connects the Spring Boot application to the MongoDB database.
Step 4: Create the MongoDB Document Class
Create a class Book.java inside the docs package.
Book.java
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "books")
public class Book {
@Id
private String id; // MongoDB ObjectId (auto-generated)
private String isbnNumber;
private String category;
private String bookName;
public String getId() {
return id;
}
public String getIsbnNumber() {
return isbnNumber;
}
public void setIsbnNumber(String isbnNumber) {
this.isbnNumber = isbnNumber;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
}
Step 5: Create the MongoDB Document Class
Create a class Book.java inside the docs package.
BookRepository.java
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.gfg.docs.Book;
public interface BookRepository extends MongoRepository<Book,Long> {
// Need to add all the required methods here
List<Book> findByCategory(String category);
Book findByBookId(long bookId);
}
Step 6: Create Service Layer
Create BookService.java inside the service package.
BookService.java
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.gfg.docs.Book;
import com.gfg.repository.BookRepository;
@Service
public class BookService {
@Autowired
private BookRepository bookRepository;
// Get all books
public List<Book> getAllBooks() {
return bookRepository.findAll();
}
// Get books by category
public List<Book> getBooksByCategory(String category) {
return bookRepository.findByCategory(category);
}
// Get book by ID (MongoDB _id)
public Book getBookById(String id) {
return bookRepository.findById(id).orElse(null);
}
// Save / Add book (clean approach)
public Book saveBook(Book book) {
return bookRepository.save(book);
}
// Delete book by ID
public boolean deleteBook(String id) {
if (bookRepository.existsById(id)) {
bookRepository.deleteById(id);
return true;
}
return false;
}
}
Step 7: Create Controller Class
Create BookController.java inside the controller package.
BookController.java
import com.gfg.docs.Book;
import com.gfg.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private BookService bookService;
// GET all books
@GetMapping
public List<Book> getAllBooks() {
return bookService.getAllBooks();
}
// GET book by ID
@GetMapping("/{id}")
public Book getBookById(@PathVariable String id) {
return bookService.getBookById(id);
}
// GET books by category
@GetMapping("/category/{category}")
public List<Book> getBooksByCategory(@PathVariable String category) {
return bookService.getBooksByCategory(category);
}
// POST (Add book)
@PostMapping
public Book addBook(@RequestBody Book book) {
return bookService.saveBook(book);
}
// DELETE book
@DeleteMapping("/{id}")
public String deleteBook(@PathVariable String id) {
boolean deleted = bookService.deleteBook(id);
return deleted ? "Book deleted successfully" : "Book not found";
}
}
Main file that contains the main method and can be used to run as a Java applicationÂ
Step 8: Build the Maven Project
Run the following command:
mvn clean install # As this is maven project
This will compile the project and download dependencies.
Step 9: Run the Application
Run the Spring Boot application using:
mvn spring-boot:run
Output:

Step 10: Test the APIs
We can test the same in the below ways. First, let us add the book
URL: http://localhost:8080/addBook?bookId=1&isbnNumber=12345&bookName=JavaBasics&category=Programming

Now list out the books
URL: http://localhost:8080/getAllBooks

Let's add 2 more books

We can search books by means of categoryÂ
URL: http://localhost:8080/getBook?category=Programming

Similarly, we can do it by bookId as well

Like this, we can do all business logic as per our needs. It is quite easier to integrate MongoDB with SpringBoot technologies.