SoFunction
Updated on 2025-03-08

Detailed explanation of the steps to integrate MongoDB Template in Spring Boot

introduction

Spring Boot is a fast development framework that enables Java developers to easily create standalone, production-level Spring applications. MongoDB is a popular NoSQL database suitable for handling large amounts of unstructured data. This article will provide a detailed introduction to how to integrate MongoDB Template in Spring Boot 3.4.0 to build a simple application from scratch.

Preparation

1. Environmental Requirements

  • Java 17 or later
  • Maven 3.6.0 or later
  • MongoDB database (can be installed locally or use MongoDB Atlas)

2. Create a Spring Boot project

You can use Spring Initializr to quickly create projects:

  • accessSpring Initializr
  • Select the following configuration:
    • Project: Maven Project
    • Language: Java
    • Spring Boot: 3.4.0
    • Project Metadata:
      • Group:
      • Artifact: mongodb-demo
      • Name: mongodb-demo
      • Package Name:
      • Packaging: Jar
      • Java: 17
  • Dependency selection:
    • Spring Web
    • Spring Data MongoDB

ClickGenerateDownload the project and unzip it.

3. Import the project

Use an IDE such as IntelliJ IDEA or Eclipse to import the Maven project you just created.

Configure MongoDB

1. Add MongoDB dependencies

exist, make sure the following dependencies exist:

<dependency>
    <groupId></groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

2. Configure database connections

existsrc/main/resources/In, add MongoDB connection configuration:

=mongodb://localhost:27017/testdb

HeretestdbIt is the database name you want to connect to, make sure the MongoDB service is running.

Create a data model

1. Create entity class

existsrc/main/java/com/example/mongodbIn the directory, create aEntity class:

package ;
import ;
import ;
@Document(collection = "users")
public class User {
    @Id
    private String id;
    private String name;
    private String email;
    // Getters and Setters
    public String getId() {
        return id;
    }
    public void setId(String id) {
         = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
         = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
         = email;
    }
}

Create a Repository

1. Create a data access interface

existsrc/main/java/com/example/mongodbIn the directory, create aInterface:

package ;
import ;
public interface UserRepository extends MongoRepository<User, String> {
    User findByEmail(String email);
}

Create a service layer

1. Create a service class

existsrc/main/java/com/example/mongodbIn the directory, create aClass:

package ;
import ;
import ;
import ;
@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
    public User saveUser(User user) {
        return (user);
    }
    public List<User> getAllUsers() {
        return ();
    }
    public User getUserByEmail(String email) {
        return (email);
    }
}

Create a controller

1. Create a REST controller

existsrc/main/java/com/example/mongodbIn the directory, create aClass:

package ;
import ;
import ;
import .*;
import ;
@RestController
@RequestMapping("/api/users")
public class UserController {
    @Autowired
    private UserService userService;
    @PostMapping
    public ResponseEntity<User> createUser(@RequestBody User user) {
        User savedUser = (user);
        return (savedUser);
    }
    @GetMapping
    public ResponseEntity<List<User>> getAllUsers() {
        List<User> users = ();
        return (users);
    }
    @GetMapping("/{email}")
    public ResponseEntity<User> getUserByEmail(@PathVariable String email) {
        User user = (email);
        return (user);
    }
}

Run the application

1. Start MongoDB service

Make sure the MongoDB service is running. If using local MongoDB, you can start it from the command line:

mongod

2. Run the Spring Boot application

Run in IDE, or use Maven on the command line:

mvn spring-boot:run

3. Test API

The API can be tested using Postman or curl.

Create a user

curl -X POST http://localhost:8080/api/users -H "Content-Type: application/json" -d '{"name":"John Doe", "email":"john@"}'

Get all users

curl http://localhost:8080/api/users

Get users through email

curl http://localhost:8080/api/users/john@

Summarize

Through the above steps, we successfully integrated MongoDB Template in Spring Boot 3.4.0, creating a simple user management API. It can be further expanded to add more features, such as user updates, deletion, etc. Hope this article helps you understand how to develop applications using Spring Boot and MongoDB!

This is the end of this article about the detailed steps of Spring Boot Integration MongoDB Template. For more related Spring Boot Integration MongoDB Template content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!