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.
open https://www.mongodb.com/try/download/community and download relevant package according to your operating system.
install the package in your system by dpkg command
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.
install the package in your system by dpkg command
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.
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
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; }
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); } }
open swagger http://localhost:9090/swagger-ui/index.html and try out POST /product api
we can also verify the insertion of product by MongoDB Compass
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(); } }
open swagger http://localhost:9090/swagger-ui/index.html and try out GET /product-repo/{id} api