Spring Boot Starter Data MongoDB Example


In this tutorial, we will take a look at how to use MongoDB as a database for your Spring Boot Application.

In software development, using a NoSQL database like MongoDB can provide flexibility and scalability for applications that deal with large amounts of unstructured or semi-structured data.

MongoDB is a popular document-oriented NoSQL database that can be easily integrated with Java applications.

For this tutorial, we will use MongoDB as our primary database. We'll keep the application simple so that it's easy to understand the concept of working with MongoDB in a Spring Boot application.



Step 1: MongoDB configuration

applications.properties

#MongoDB
spring.data.mongodb.uri=mongodb://localhost:27017/mydatabase
spring.data.mongodb.database=mydatabase

Note: Make sure you have MongoDB installed and running on your local machine, or update the URI to point to your MongoDB instance.



Gradle Configuration

plugins {
    id 'java'
    id 'org.springframework.boot' version '3.0.6'
    id 'io.spring.dependency-management' version '1.1.0'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-validation'
    implementation 'org.jetbrains:annotations:23.0.0'
}

tasks.named('test') {
    useJUnitPlatform()
}

Step 2: Our Entity

Keeping it really simple with id, userId and userName fields.

package com.example.mongodemo;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "users")
public class User {

    @Id
    private String id;

    private int userId;
    private String userName;

    public User(int userId, String userName) {
        this.userId = userId;
        this.userName = userName;
    }

    public User() {
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
}

Step 3: Spring Data MongoDB Repository for User

package com.example.mongodemo;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface UserRepository extends MongoRepository {

    Optional findByUserId(Integer userId);

    void deleteByUserId(Integer userId);
}

Step 4: User Service class

package com.example.mongodemo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class UserService {

    @Autowired
    UserRepository userRepository;

    public Optional findUserByUserId(Integer userId) {
        System.out.println("User fetched from MongoDB!");
        return userRepository.findByUserId(userId);
    }

    public User save(User user) {
        return userRepository.save(user);
    }

    public void updateUser(Integer userId, String userName) {
        userRepository.findByUserId(userId).ifPresent(user -> {
            user.setUserName(userName);
            userRepository.save(user);
        });
    }

    public void deleteUserByUserId(Integer userId) {
        userRepository.deleteByUserId(userId);
    }
}

Step 5: User Controller

package com.example.mongodemo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping(path = "/get-user/{userId}")
    public Optional getUserName(@PathVariable("userId") int userId) {
        return userService.findUserByUserId(userId);
    }

    @PostMapping(path = "/add-user")
    public void addUser(@RequestBody User user) {
        System.out.println("User Saved!");
        userService.save(user);
    }

    @PostMapping(path = "/update-user")
    public void updateUser(@RequestBody User user) {
        System.out.println("User Updated!");
        userService.updateUser(user.getUserId(), user.getUserName());
    }

    @DeleteMapping(path = "/delete-user/{userId}")
    public void deleteUser(@PathVariable("userId") int userId) {
        System.out.println("User Deleted!");
        userService.deleteUserByUserId(userId);
    }
}

As you may see, we have performed all CRUD operations using Spring Data MongoDB, integrating MongoDB as our primary database for the Spring Boot application.


CRUD Operations cURL Commands

  1. Create User:

    curl --location 'http://localhost:8080/add-user' \
    --header 'Content-Type: application/json' \
    --data '{
        "userId": 10,
        "userName": "Harry"
    }'
  2. Retrieve User:

    curl --location 'http://localhost:8080/get-user/10' \
    --header 'Content-Type: application/json'
  3. Update User:

    curl --location 'http://localhost:8080/update-user' \
    --header 'Content-Type: application/json' \
    --data '{
        "userId":10,
        "userName":"Ron"
    }'
  4. Delete User:

    curl --location --request DELETE 'http://localhost:8080/delete-user/10'

Facing issues? Have Questions? Post them here! I am happy to answer!







Author Info:

Rakesh (He/Him) has a Masters Degree in Computer Science with over 15+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap