Spring Boot – CRUD Operations using MongoDB

28 Dec, 2021
CRUD stands for Create, Read/Retrieve, Update and Delete and these are the four basic operations that we perform on persistence storage. CRUD is data-oriented and the standardized use of HTTP methods. HTTP has a few methods which work as CRUD operations and do note they are very vital from a developmental point perspective in programming that also does helps us relate better web development and also aids us while dealing with databases. 
So, standard CRUD Operations is as follows:
POST: Creates a new resource
GET: Reads/Retrieve a resource
PUT: Updates an existing resource
DELETE: Deletes a resource
As the name suggests 
CREATE Operation: Performs the INSERT statement to create a new record.
READ Operation: Reads table records based on the input parameter.
UPDATE Operation: Executes an update statement on the table. It is based on the input parameter.
DELETE Operation: Deletes a specified row in the table. It is also based on the input parameter.
So in this article, we are going to perform some basic CRUD Operations by creating a Spring Boot Application and using the MySQL Database. So here is a brief explanation of What’s Spring Boot and What’s MySQL Database. 
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because it’s a rapid production-ready environment that enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time.
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for the storage and retrieval of data. This format of storage is called BSON ( similar to JSON format). A simple MongoDB document Structure: 
{
 title: 'GeeksforGeeks',
 by: 'Amiya Rout',
 url: 'https://www.geeksforgeeks.org',
 type: 'NoSQL'
} 
MongoDB Compass is a powerful GUI for querying, aggregating, and analyzing your MongoDB data in a visual environment. Compass is free to use and source available and can be run on macOS, Windows, and Linux.
So to connect and perform CRUD operation with the MongoDB with Spring Boot application we have to just configure it inside the application.properties file as follows:
# Configuration for MongoDB

spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=BookStore (Here BookStore is my database name)
MongoRepository is an interface provided by Spring Data in the package org.springframework.data.mongodb.repository. MongoRepository extends the PagingAndSortingRepository and QueryByExampleExecutor interfaces that further extend the CrudRepository interface. MongoRepository provides all the necessary methods which help to create a CRUD application and it also supports the custom derived query methods.
Syntax:
public interface MongoRepository<T,ID> 
extends PagingAndSortingRepository<T,ID>, QueryByExampleExecutor<T>
Where
T: Domain type that repository manages (Generally the Entity/Model class name)
ID: Type of the id of the entity that repository manages (Generally the wrapper class of your @Id that is created inside the Entity/Model class)
Illustration:
public interface BookRepo extends MongoRepository<Book, Integer> {}
Example: We will be making a Spring Boot application that manages a Book entity with MongoRepository. The data is saved in the MongoDB database. We use a RESTful controller.
Step 1: Refer to this article How to Create a Spring Boot Project with IntelliJ IDEA and create a Spring Boot project. 
Step 2: Add the following dependency
Spring Web
MongoDB
Lombok
DevTools
Below is the complete code for the pom.xml file. Please check if you have missed something.
XML
<?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.6.0</version>        <relativePath/> <!-- lookup parent from repository -->    </parent>    <groupId>com.globallogic</groupId>    <artifactId>spring-mongodb</artifactId>    <version>0.0.1-SNAPSHOT</version>    <name>spring-mongodb</name>    <description>Demo project for Spring Boot</description>    <properties>        <java.version>11</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>        </dependency>    </dependencies>      <build>        <plugins>            <plugin>                <groupId>org.springframework.boot</groupId>                <artifactId>spring-boot-maven-plugin</artifactId>                <configuration>                    <excludes>                        <exclude>                            <groupId>org.projectlombok</groupId>                            <artifactId>lombok</artifactId>                        </exclude>                    </excludes>                </configuration>            </plugin>        </plugins>    </build>  </project>
Step 3: Create 3 packages and create some classes and interfaces inside these packages as seen in the below image
model
repository
controller
Note:
Green Rounded Icon ‘I’ Buttons are Interface
Blue Rounded Icon ‘C’ Buttons are Classes
Step 4: Inside the entity package
Creating a simple POJO class inside the Book.java file.
Example
Java
// Java Program to illustrate Book File  // Importing required classesimport lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;import org.springframework.data.annotation.Id;import org.springframework.data.mongodb.core.mapping.Document;  // Annotations@Data@NoArgsConstructor@AllArgsConstructor@Document(collection = "Book")  // Classpublic class Book {      // Attributes    @Id private int id;    private String bookName;    private String authorName;}
Step 5: Inside the repository package
Create a simple interface and name the interface as BookRepo. This interface is going to extend the MongoRepository as we have discussed above.
Example
Java
// Java Program to Illustrate BookRepo File  import com.globallogic.spring.mongodb.model.Book;import org.springframework.data.mongodb.repository.MongoRepository;  public interface BookRepo    extends MongoRepository<Book, Integer> {}
Step 6: Inside the controller package
Inside the package create one class named as BookController.
Java
import com.globallogic.spring.mongodb.model.Book;import com.globallogic.spring.mongodb.repository.BookRepo;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*;  import java.util.List;  // Annotation @RestController  // Class public class BookController {      @Autowired    private BookRepo repo;      @PostMapping("/addBook")    public String saveBook(@RequestBody Book book){        repo.save(book);                return "Added Successfully";    }      @GetMapping("/findAllBooks")    public List<Book> getBooks() {                return repo.findAll();    }      @DeleteMapping("/delete/{id}")    public String deleteBook(@PathVariable int id){        repo.deleteById(id);                return "Deleted Successfully";    }  }
Step 7: Below is the code for the application.properties file
server.port = 8989

# MongoDB Configuration
server.port:8989
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=BookStore
Step 8: Inside the MongoDB Compass
Go to your MongoDB Compass and create a Database named BookStore and inside the database create a collection named Book as seen in the below image
Now run your application and let’s test the endpoints in Postman and also refer to our MongoDB Compass.
Testing the Endpoint in Postman
Endpoint 1: POST – http://localhost:8989/addBook
Endpoint 2: GET – http://localhost:8989/findAllBooks
Endpoint 3: DELETE – http://localhost:8989/delete/1329
Finally, MongoDB Compass is as depicted in the below image as shown below as follows:
Java-Spring-Boot
Java
MongoDB
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.