Spring Boot MongoDB CRUD Example

MongoDB is one of the popular document-based No-SQL databases used for developing web applications. Usage of NoSQL databases instead of the traditional databases, provides advantages like improved performance, efficiency, etc.

In this post, we will learn how to perform CRUD operations by using Spring boot application with MongoDB database.

We will use

  • Spring boot – Version 2.2.4.RELEASE
  • Lombok
  • Java version 1.8
  • MongoDB(For the Windows)

We will install MongoDB on the Windows system in the next step.

Table of Contents

Set up MongoDB database on Windows

In this section, we will set up the MongoDB database and the required tool to browse the database.

Set up MongoDB database

Download the MongoDB database from the MongoDB website. Also, extract the downloaded zip file. Navigate to the /bin directory, as shown below.

MongoDB installation Windows

To start the MongoDB server, open the command prompt and type ‘mongod’, as shown in the below image.

MongoDB installation Windows

Once the MongoDB server starts successfully, we should be able to see that the server is listening on default port number 27017.

MongoDB installation Windows

In case of any error, make sure that the directory structure /data/db is present under the current directory.

Set up MongoDB compass

To browse the MongoDB database, we have to download the MongoDB compass. Extract the downloaded zip file, navigate inside the extracted folder, and finally run the MongoDBCompass.exe file.

Spring Boot MongoDB CRUD example

Enter the MongoDB connection string as shown in the new connection dialog, and click on the connect button.

Spring Boot MongoDB CRUD example

Create a new database by clicking on the Create database button with the name School with a collection name called Student.

Spring Boot MongoDB CRUD example

Finally, we have our MongoDB database setup ready. Now, we can create our Spring boot application.

Create the Spring boot application

Create the Spring boot application with the required dependencies. Add spring-boot-starter-web, spring-boot-starter-data-mongodb and lombok dependencies.

Also, the spring-boot-starter-data-mongodb library gives the required support for connecting the spring boot application with the MongoDB database.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.asb.example</groupId>
    <artifactId>spring-boot-mangodb-crud-example</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-mangodb-crud-example</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
        <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Add the MongoDB connection string to the created Spring boot application’s application.properties file.

spring.data.mongodb.uri=mongodb://localhost:27017/School

Create the Student class

Create a java class with the name Student and add the required fields, as shown below.

Also, annotate the class with the @Document annotation. This annotation specifies this class as a MongoDB document.

We have also defined the ‘id’ field with string datatype. This will automatically assign an auto-generated value to the ‘id’ field.

package com.asb.example.model;

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

@Getter
@Setter
@Document(collection="Student")
public class Student {

    @Id
    private String id;
    private String name;
    private String grade;
}

Create the repository

Create a new repository interface with the name StudentRepository and also extend the MongoRepository repository. This is similar to the JPA repository, where we extend the JpaRepository interface.

package com.asb.example.repository;

import org.springframework.data.mongodb.repository.MongoRepository;
import com.asb.example.model.Student;

public interface StudentRepository extends MongoRepository<Student, String> {
}

Create the service layer

Create a spring service class with the name StudentService, and also add the methods to support the CRUD operation on the Student document.

package com.asb.example.service;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.asb.example.model.Student;
import com.asb.example.repository.StudentRepository;

@Service
public class StudentService {

    @Autowired
    private StudentRepository studentRepository;
    
    public List<Student> getStudents() {
        return studentRepository.findAll();
    }
    
    public Student saveStudent(Student student) {
        return studentRepository.save(student);
    }
    
    public Student updateStudent(Student student) {
        return studentRepository.save(student);
    }
    
    public String getStudent(String id) {
        studentRepository.deleteById(id);
        return "Student with id: " + id + " deleted successfully";
    }
}

Add the resource layer

Create a REST controller class with the name StudentController and add the required method for CRUD operations.

package com.asb.example.resource;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.asb.example.model.Student;
import com.asb.example.service.StudentService;

@RestController
public class StudentController {

    @Autowired
    private StudentService studentService;

    @GetMapping("/students")
    public ResponseEntity<List<Student>> getStudents() {
        List<Student> students = studentService.getStudents();
        return new ResponseEntity<>(students, HttpStatus.OK);
    }

    @PostMapping("/student")
    public ResponseEntity<Student> saveStudent(@RequestBody Student student) {
        Student s = studentService.saveStudent(student);
        return new ResponseEntity<>(s, HttpStatus.CREATED);
    }

    @PutMapping("/student")
    public ResponseEntity<Student> updateStudent(@RequestBody Student student) {
        Student s = studentService.updateStudent(student);
        return new ResponseEntity<>(s, HttpStatus.CREATED);
    }

    @DeleteMapping("/student")
    public ResponseEntity<String> deleteStudent(@RequestParam(name = "id") String id) {
        String message = studentService.getStudent(id);
        return new ResponseEntity<>(message, HttpStatus.OK);
    }
}

We have successfully created REST endpoints using Spring boot and MongoDB to perform CRUD operations on the Student object that gets stored in the MongoDB database.

Testing the application

Start the Spring boot application.

Create an object of the student by sending the required values to the postman, as shown below.

Spring Boot MongoDB CRUD example

We can observe the created object of Student in the MongoDB database.

MongoDB compass

Retrieve the student details by using the GET endpoint.

Spring Boot MongoDB CRUD example

Update the student details with the help of the PUT endpoint.

Spring Boot MongoDB CRUD example

Delete the Student object by sending the ‘id’ request parameter.

Spring Boot MongoDB CRUD example

Conclusion

In this post, we learned how to perform CRUD operations with the Spring boot MongoDB application. We also learned how to set up the MongoDB database on the Windows system.

Example source code is available on GitHub.

Spring Boot MongoDB CRUD Example
Scroll to top

Discover more from ASB Notebook

Subscribe now to keep reading and get access to the full archive.

Continue reading