CRUD Operations in MongoDB with Spring Boot

One solid reason to choose a NoSQL database over a traditional SQL database is scalability and flexibility. NoSQL databases are designed to handle large amounts of data and can easily scale horizontally by adding more servers or nodes. This makes them an ideal choice for applications with rapidly growing data requirements, such as social media platforms, e-commerce websites, and big data analytics.

MongoDB, a popular NoSQL database, offers a flexible and scalable solution for data storage. When combined with Spring Boot, a powerful Java framework, you can easily perform CRUD (Create, Read, Update, Delete) operations on MongoDB. In this blog, we'll explore how to implement CRUD operations in MongoDB using Spring Boot.

1. Installing MongoDB

open https://www.mongodb.com/try/download/community and download relevant package according to your operating system.

mongodb portal

install the package in your system by dpkg command

mongodb portal

also we need mongo shell to interact with MongoDB databases.

open https://www.mongodb.com/try/download/shell and download relevant package according to your operating system.

mongodb portal

install the package in your system by dpkg command

2. Setting Up the Project

Let's start by creating a new Spring Boot project. You can do this through Spring Initializr or your preferred development environment. Make sure to include the required dependencies for Spring Data MongoDB.

Configuring MongoDB Connection

In your Spring Boot project, configure the MongoDB connection by modifying the application.properties or application.yml file. Specify the MongoDB connection details, such as the host, port, and database name. For example:

            spring.data.mongodb.host=127.0.0.1
            spring.data.mongodb.port=27017
            spring.data.mongodb.database=mydatabase
            

Creating a Model

Define the data structure that you want to store in MongoDB by creating a model class. Annotate the class with @Document to indicate that it's a MongoDB document, and use @Field annotations to map fields to document fields.

            package com.vivek.mongodbdemo.model;

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

            /**
             * @author viveksoni
             */

            @Data
            @Document
            public class Product {

                @Id
                private String id;
                private String name;
                private double price;

            }
            

Building a RESTful API

You can expose these CRUD operations as a RESTful API by creating a controller. Use Spring's @RestController annotation to define the REST endpoints and handle incoming HTTP requests. Map the endpoints to your CRUD operations.

            package com.vivek.mongodbdemo.controller;

            import com.vivek.mongodbdemo.model.Product;
            import org.springframework.beans.factory.annotation.Autowired;
            import org.springframework.data.mongodb.core.MongoTemplate;
            import org.springframework.data.mongodb.core.query.Criteria;
            import org.springframework.data.mongodb.core.query.Query;
            import org.springframework.web.bind.annotation.*;

            /**
             * @author viveksoni
             */

            @RestController
            @RequestMapping("/products")
            public class ProductController {

                @Autowired
                private MongoTemplate mongoTemplate;


                @PostMapping
                public Product createProduct(@RequestBody Product product) {
                    return mongoTemplate.save(product);
                }

                @GetMapping("/{id}")
                public Product getProductById(@PathVariable String id) {
                    return mongoTemplate.findById(id, Product.class);
                }

                @PutMapping("/{id}")
                public Product updateProduct(@RequestBody Product updatedProduct) {
                    return mongoTemplate.save(updatedProduct);
                }

                @DeleteMapping("/{id}")
                public void deleteProduct(@PathVariable String id) {
                    mongoTemplate.remove(Query.query(Criteria.where("id").is(id)), Product.class);
                }

            }
            

Testing Your CRUD Operations

open swagger http://localhost:9090/swagger-ui/index.html and try out POST /product api

swagger api testing

we can also verify the insertion of product by MongoDB Compass

swagger api testing

3. CRUD using MongoRepository

create a product repository and extend it with MongoRepository<T,ID>

            package com.vivek.mongodbdemo.repository;

            import com.vivek.mongodbdemo.model.Product;
            import org.springframework.data.mongodb.repository.MongoRepository;

            /**
             * @author viveksoni
             */

            public interface ProductRepository extends MongoRepository<Product, String> {

            }
            

create a new controller class and autowire newly created repository

            package com.vivek.mongodbdemo.controller;

            import com.vivek.mongodbdemo.model.Product;
            import com.vivek.mongodbdemo.repository.ProductRepository;
            import org.springframework.beans.factory.annotation.Autowired;
            import org.springframework.web.bind.annotation.GetMapping;
            import org.springframework.web.bind.annotation.PathVariable;
            import org.springframework.web.bind.annotation.RequestMapping;
            import org.springframework.web.bind.annotation.RestController;

            import java.util.Optional;

            /**
             * @author viveksoni
             */

            @RestController
            @RequestMapping("/products-repo")
            public class ProductRepoController {

                @Autowired
                private ProductRepository productRepository;

                @GetMapping("/{id}")
                public Product getProductById(@PathVariable String id) {
                    Optional<Product> product = productRepository.findById(id);
                    return product.get();
                }

            }
            

Testing Your CRUD Operations

open swagger http://localhost:9090/swagger-ui/index.html and try out GET /product-repo/{id} api

swagger api testing


source code

Get in touch

Let’s work together

Reach out if you have a concept for a website or mobile app or require guidance with product design. contact me.
  info@whywhytechnova.com
  +(91) 88661 28862