$show=/label

Spring Boot MongoDB CRUD Operations Example

SHARE:

A quick guide to How to implement MongoDB CRUD Operations in Spring Boot Applications. Example Spring Boot Application to Create, Read, Update, and Delete methods along with testing with postman tool.

1. Introduction


In this tutorial, You'll learn how to do CRUD operations in MongoDB database as part of the Spring Boot Application.

MongoDB is a NoSQL database that uses JSON as a schema.

CRUD operations have been considered in computer programming as create, read, update, and delete (CRUD) are the four basic functions of persistent storage

Another example of How to generate auto-increment id in MongoDB Spring Boot App

Let us see step by step how to do it in a simple way.

Spring Boot MongoDB CRUD Operations Example




MongoDB CRUD Examples in Spring Boot App


2. Adding Dependencies for MongoDB CRUD Operations

Add the web, MongoDB, and Lombok dependencies to the spring boot project.

  • spring-boot-starter-web
  • spring-boot-starter-data-mongodb
  • org.projectlombok&
[post_ads]

<?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.6.RELEASE</version>
  <relativePath/> <!-- lookup parent from repository -->
 </parent>
 <groupId>com.javaprogramto.springboot</groupId>
 <artifactId>MongoDB-Spring-Boot-CURD</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <name>MongoDB-Spring-Boot-CURD</name>
 <description>Demo project for Spring Boot</description>

 <properties>
  <java.version>1.8</java.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.springframework.boot</groupId>
   <artifactId>spring-boot-devtools</artifactId>
   <scope>runtime</scope>
   <optional>true</optional>
  </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>


3. Creating a DataBase and Collection (Table) with MongoDB Compass


Open the "MongoDB Compass" Gui and create a database along with the collection name "Employee".

MongoDB Compass GUI will allow us to create, add, or delete the data and visualize, debug, and optimize the data easily with the interface rather than doing the things with the script.

We are going to perform all CRUD operations on the Employee table.

Creating a DataBase and Collection (Table) with MongoDB Compass


No columns were added to the collection or table as of now. And also we are not going to create anything in this article. But if you want to add columns, you can add them as need.

Whatever the object is passing to the MongoDB, based on the object properties columns will be added to the Employee table.

4. Creating Model Class - To store the data into MongoDB


We've already injected the Lombok dependency which makes the code simple and easy to main with the annotations rather than keep much code in the class.

@Getter annotation to generate the getter methods at runtime.
@Setter annotation to generate the setter methods at runtime
@ToString to generate the toString() method with all the properties and its values.

And also linking this model to MongoDB table with @Document annotation and specify the table name with collection attribute to tell the table name as "Employee"


package com.javaprogramto.springboot.model;

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

import java.util.Date;

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

    @Id    
    private int id;
    private String name;
    private int age;
    private long phoneNumber;
    private Date dateOfJoin;


}


5. Create Repository - CRUD Operations with MongoRepository<Employee, Integer>


Let us create a package with the repository and create an interface with the name "EmployeeRepository".
This interface must extend the built-in MongoReposity<T, ID>.

Here T is the type of the object that CURD operations to be performed on and ID is the primary key that is used for fetching.

package com.javaprogramto.springboot.MongoDBSpringBootCURD.repository;

import com.javaprogramto.springboot.model.Employee;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface EmployeeRepository extends MongoRepository<Employee, Integer> {

    
}

Inside EmployeeRepositiry interface, We did not add any methods because all basic methods come from MongoRepository.
[post_ads]

6. Create Controller - API Endpoints for Doing CRUD Operations in MongoDB


Create a class with any name, but here created as "EmployeeController" and it should be annotated with @RestController annotation.

And also need to provide the URL mapping with annotation @RequestMapping.

All these annotations are should be applied at the class level.

package com.javaprogramto.springboot.MongoDBSpringBootCURD.controller;

import com.javaprogramto.springboot.MongoDBSpringBootCURD.model.Employee;
import com.javaprogramto.springboot.MongoDBSpringBootCURD.repository.EmployeeRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping
("/employee")

public class EmployeeController {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private EmployeeRepository employeeRepository;

    @PostMapping
("/add")
    public String saveEmployee(@RequestBody Employee e) {


        employeeRepository.insert(e);

        return "Added Employee id " + e.getId();
    }

    @GetMapping("/find/{id}")

    public Optional<Employee> getEmployee(@PathVariable int id) {

        logger.info("find employee by id : "+id);
        Optional<Employee> emp = employeeRepository.findById(id);

        return emp;
    }

    @GetMapping("/all")

    public List<Employee> getAllEmployee() {

        List<Employee> allEmployees = employeeRepository.findAll();

        return allEmployees;
    }

    @DeleteMapping("/delete/{id}")

    public String deleteEmployee(@PathVariable int id) {

        employeeRepository.deleteById(id);

        return "Delete emp for id " + id;
    }

    @PutMapping("/update")

    public String updateEmployee(@RequestBody Employee e) {

        employeeRepository.save(e);

        return "Updated Employee for id " + e.getId();
    }
}

This example is having all the CURD operations.

6.1 Create or Insert Operation


Create a post request that is mapped to the "/add" URL. When hitting this URL employe should be passed as JSON that will be mapped to Employee object with @RequestBody.


@PostMapping("/add")

public String saveEmployee(@RequestBody Employee e) {

    employeeRepository.insert(e);

    return "Added Employee id " + e.getId();
}

[post_ads]

6.2 Read Operations


Get All Employees:

@GetMapping("/all")

public List<Employee> getAllEmployee() {

    List<Employee> allEmployees = employeeRepository.findAll();

    return allEmployees;
}

Get Employee By Id:


@GetMapping("/find/{id}")


public Optional<Employee> getEmployee(@PathVariable int id) {

    logger.info("find employee by id : "+id);
    Optional<Employee> emp = employeeRepository.findById(id);

    return emp;
}

6.3 Update Operation


Updating an existing employee

@PutMapping("/update")

public String updateEmployee(@RequestBody Employee e) {

    employeeRepository.save(e);

    return "Updated Employee for id " + e.getId();
}

6.4 Delete Operation


Deleting an existing employee

@DeleteMapping("/delete/{id}")


public String deleteEmployee(@PathVariable int id) {

    employeeRepository.deleteById(id);

    return "Delete emp for id " + id;
}

7. Configuring the MongoDB in the Spring Boot Application


Before starting the application, we need to configure MongoDB NoSQL database details in the application.properties file as below.

If you don't port and database name, you can get the port from log or console and database name from MongoDB Compass GUI.

spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=JavaProgramTo


8. Testing the CRUD Operations of Spring Boot MongoDB


We used postman for testing and which is more flexible to test all endpoints.

Add: localhost:8080/employee/add
Delete by id : localhost:8080/employee/delete/100
Find by id: Delete: localhost:8080/employee/find/100
Find all: Delete: localhost:8080/employee/all
Update: localhost:8080/employee/update

[post_ads]

8.1 Add or Create Operation with PostMan Tool


spring-boot-mongodb-add-crud-operation-min



8.2 Read Operation - Get All Employees with PostMan Tool


spring-boot-mongodb-get-all-crud-operation-min


[post_ads]

8.3 Read Operation - Get Employee By Id -  with PostMan Tool


spring-boot-mongodb-find-by-id-crud-operation-min

8.4 Update Employee -  with PostMan Tool


Employee table before update

employee-table-records-before-update-200-min


Updating employee id 200 name and phone number values.
[post_ads]

spring-boot-mongodb-update-crud-operation-min


Employee table After successful update.

employee-table-records-after-update-200-min

8.5 Delete Operation with PostMan Tool


Deleting employee id = 100

spring-boot-mongodb-delete-crud-operation-min

Employee table after delete.
[post_ads]

deleted-employee-id-100-min



9. Exceptions in MongoDB CRUD Operations Spring Boot


If you invalid number to phone number filed with spaces or special characters then you will face the below error at run time

2020-05-07 20:11:02.155  WARN 36206 --- [nio-8080-exec-5] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `long` from String "+1 6778 100 100": not a valid Long value; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `long` from String "+1 6778 100 100": not a valid Long value

 at [Source: (PushbackInputStream); line: 6, column: 16] (through reference chain: com.javaprogramto.springboot.MongoDBSpringBootCURD.model.Employee["phoneNumber"])]

2020-05-07 20:11:16.038  WARN 36206 --- [nio-8080-exec-7] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `long` from String "1 6778 100 100": not a valid Long value; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `long` from String "1 6778 100 100": not a valid Long value

 at [Source: (PushbackInputStream); line: 6, column: 16] (through reference chain: com.javaprogramto.springboot.MongoDBSpringBootCURD.model.Employee["phoneNumber"])]

10. SpringBoot MongoDB Project Structure

├── HELP.md
├── MongoDB-Spring-Boot-CURD.iml
├── mvnw
├── mvnw.cmd
├── pom.xml
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com
│   │   │       └── javaprogramto
│   │   │           └── springboot
│   │   │               └── MongoDBSpringBootCURD
│   │   │                   ├── MongoDbSpringBootCurdApplication.java
│   │   │                   ├── controller
│   │   │                   │   └── EmployeeController.java
│   │   │                   ├── model
│   │   │                   │   └── Employee.java
│   │   │                   └── repository
│   │   │                       └── EmployeeRepository.java
│   │   └── resources
│   │       ├── application.properties
│   │       ├── static
│   │       └── templates


11. Conclusion



In conclusion, You've seen how to build the CRUD operations with MongoDB in the Spring Boot application.


Example of how to add all endpoints implemented for insertion, deletion, update and find operations.

Screenshots for all operations are shown.


All the code is shown in this article is over GitHub.

You can download the project directly and can run in your local without any errors.



If you have any queries please post in the comment section.

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,16,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,23,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,84,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,13,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,10,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,30,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,78,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,93,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Logging,1,Mac OS,2,Math,1,Matrix,5,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,23,String,58,String Programs,12,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Spring Boot MongoDB CRUD Operations Example
Spring Boot MongoDB CRUD Operations Example
A quick guide to How to implement MongoDB CRUD Operations in Spring Boot Applications. Example Spring Boot Application to Create, Read, Update, and Delete methods along with testing with postman tool.
https://1.bp.blogspot.com/-vIWkbakn0eU/XrRN172MOcI/AAAAAAAACpI/xNTv34uEQf4x7qRC18jyYA_sd-Vgh3jEACLcBGAsYHQ/s640/Spring%2BBoot%2BMongoDB%2BCRUD%2BOperations%2BExample.png
https://1.bp.blogspot.com/-vIWkbakn0eU/XrRN172MOcI/AAAAAAAACpI/xNTv34uEQf4x7qRC18jyYA_sd-Vgh3jEACLcBGAsYHQ/s72-c/Spring%2BBoot%2BMongoDB%2BCRUD%2BOperations%2BExample.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/05/spring-boot-mongodb-crud.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/05/spring-boot-mongodb-crud.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content