Introduction
Here we will see a post on Spring Boot MongoDB CRUD example, where CRUD means Create, Read, Update, and Delete operations. For performing CRUD operations on MongoDB through Spring Boot framework, we need to add required dependency. We will use Spring REST controller to expose our MongoDB CRUD operations onto REST or RESTful API.
You may also like to read Spring Boot Data JPA CRUD Example, Python Flask REST API MongoDB CRUD Example.
Prerequisites
Eclipse Neon, Java 1.8, Gradle 5.4.1, Spring Boot 2.1.6
Example and Source Code
Please go through the following sections to implement Spring Boot MongoDB CRUD example.
Creating Project
We will create here gradle based project in Eclipse and the project structure will look to the similar image as shown in the below figure:

Updating Build Script
Next we will update the default generated build.gradle script to include required dependencies.
In the below build script we have included spring boot web, spring boot data mongodb starters.
buildscript {
ext {
springBootVersion = '2.1.6.RELEASE'
}
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-web:${springBootVersion}")
compile("org.springframework.boot:spring-boot-starter-data-mongodb:${springBootVersion}")
}
Configuring MongoDB
As we mentioned in the prerequisites section, you need to go through Installing MongoDB in Windows to install MongoDB and create database roytuts into it.
If we do not specify anything in the application.properties or application.yml file then Spring Boot, by default, connects to test database server at localhost:27017.
Here we will specify our roytuts database for connecting to it.
Notice also we have mentioned spring.jackson.default-property-inclusion=NON_NULL
to ignore null field in JSON response.
Create below content into src/main/resources/application.properties file.
spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
spring.data.mongodb.database=roytuts
spring.jackson.default-property-inclusion=NON_NULL
Creating Entity Class
We will work with database, where we will perform CRUD operations. Therefore we need to create entity class to map out database column with Java class attributes.
We want to store user details, such as, id, name, email and password of the user.
Another beauty of Spring Boot Data MongoDB starter is the below class will create the required collection in the database. Even we didn’t mention any column name, so it will create same column name in the table as the Java attributes.
So the corresponding user entity class can be defined as:
package com.roytuts.spring.boot.mongodb.crud.entity;
import org.springframework.data.annotation.Id;
public class User {
@Id
private String id;
private String name;
private String email;
private String pwd;
//getters and setters
}
Creating VO Class
It is always good idea to create a VO or DTO class to return as a response object from REST controller instead of returning the entity class as a response object.
The VO class is also similar to the above entity class.
package com.roytuts.spring.boot.mongodb.crud.vo;
public class UserVo {
private String id;
private String name;
private String email;
private String pwd;
//getters and setters
}
Creating Repository Interface
Spring Data MongoDB provides built-in methods for performing basic CRUD operations and you don’t need to write any query method.
Another beauty of Spring Data MongoDB is that you write Java method to query your database and Spring generates the corresponding query from your method for performing database operations.
We have just extended the MongoRepository
interface but we did not write any query method inside this repository because we will use Spring’s built-in methods for performing CRUD operations.
package com.roytuts.spring.boot.mongodb.crud.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.roytuts.spring.boot.mongodb.crud.entity.User;
public interface UserRepository extends MongoRepository<User, String> {
}
Creating Service Class
The service class is used generally if you want to perform some business logic or conversion to different data.
Here in the below service method we will convert entity class to VO class using Java 8’s stream API.
We have used Java 8’s map() method to map entity to VO object.
package com.roytuts.spring.boot.mongodb.crud.service;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.roytuts.spring.boot.mongodb.crud.entity.User;
import com.roytuts.spring.boot.mongodb.crud.repository.UserRepository;
import com.roytuts.spring.boot.mongodb.crud.vo.UserVo;
@Service
public class UserService {
@Autowired
private UserRepository repository;
public List<UserVo> getUserList() {
return repository.findAll().stream().map(u -> {
UserVo vo = new UserVo();
vo.setId(u.getId());
vo.setName(u.getName());
vo.setEmail(u.getEmail());
return vo;
}).collect(Collectors.toList());
}
public UserVo getUserById(String id) {
return repository.findById(id).map(u -> {
UserVo vo = new UserVo();
vo.setId(u.getId());
vo.setName(u.getName());
vo.setEmail(u.getEmail());
return vo;
}).orElse(null);
}
public void saveUser(UserVo vo) {
User user = new User();
user.setName(vo.getName());
user.setEmail(vo.getEmail());
user.setPwd(vo.getPwd());
repository.save(user);
}
public void updateUser(UserVo vo) {
User user = new User();
user.setId(vo.getId());
user.setName(vo.getName());
user.setEmail(vo.getEmail());
user.setPwd(vo.getPwd());
repository.save(user);
}
public void deleteUser(UserVo vo) {
User user = new User();
user.setId(vo.getId());
repository.delete(user);
}
}
Creating REST Controller
Now we will expose our CRUD operations onto REST API so that any client can call our REST service and perform CRUD operations.
Exposing the operations on REST makes loosely coupled to integrate with any client technologies.
Notice how we have performed CRUD operations using the same endpoint with different HTTP methods.
package com.roytuts.spring.boot.mongodb.crud.rest.controller;
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.PathVariable;
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.RestController;
import com.roytuts.spring.boot.mongodb.crud.service.UserService;
import com.roytuts.spring.boot.mongodb.crud.vo.UserVo;
@RestController
public class UserRestController {
@Autowired
private UserService service;
@GetMapping("/user/{id}")
public ResponseEntity<UserVo> getUser(@PathVariable String id) {
return new ResponseEntity<>(service.getUserById(id), HttpStatus.OK);
}
@GetMapping("/user")
public ResponseEntity<List<UserVo>> getUserList() {
return new ResponseEntity<>(service.getUserList(), HttpStatus.OK);
}
@PostMapping("/user")
public ResponseEntity<String> saveUser(@RequestBody UserVo UserVo) {
service.saveUser(UserVo);
return new ResponseEntity<>("New user successfully saved", HttpStatus.OK);
}
@PutMapping("/user")
public ResponseEntity<String> updateUser(@RequestBody UserVo UserVo) {
service.updateUser(UserVo);
return new ResponseEntity<>("User successfully updated", HttpStatus.OK);
}
@DeleteMapping("/user")
public ResponseEntity<String> deleteUser(@RequestBody UserVo userVo) {
service.deleteUser(userVo);
return new ResponseEntity<>("User successfully deleted", HttpStatus.OK);
}
}
Creating Main Class
Creating a main would be sufficient to deploy our application into the Tomcat server. This is a great advantage that you just need to let Spring know that it is your Spring Boot Application using @SpringBootApplication
and main class.
We also need to tell Spring where our entity class and repository interface.
package com.roytuts.spring.boot.mongodb.crud.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
@EntityScan("com.roytuts.spring.boot.mongodb.crud.entity")
@EnableMongoRepositories("com.roytuts.spring.boot.mongodb.crud.repository")
@SpringBootApplication(scanBasePackages = "com.roytuts.spring.boot.mongodb.crud")
public class SpringMongoDbJpaCrudApp {
public static void main(String[] args) {
SpringApplication.run(SpringMongoDbJpaCrudApp.class, args);
}
}
Running the Application
Run the main class to start the application. The application will start on embedded Tomcat server’s port 8080.
Testing the Application
As we know that we don’t have any data into the database so we will first create new website and store into database.
Creating user
Request Method – POST
Request URL – http://localhost:8080/user
Request Body
{
"name":"Soumitra",
"email":"contact@roytuts.com",
"pwd":"pwd"
}
Response – New user successfully saved
Reading User
All Users
Request Method – GET
Request URL – http://localhost:8080/user
Response
Array[1]
0: {
"id": "5d1c88a45ed21a532cb07a46",
"name": "Soumitra",
"email": "contact@roytuts.com"
}
]
Single User
Request Method – GET
Request URL – http://localhost:8080/user/5d1c88a45ed21a532cb07a46
Response
{
"id": "5d1c88a45ed21a532cb07a46",
"name": "Soumitra",
"email": "contact@roytuts.com"
}
Updating User
Request Method – POST
Request URL – http://localhost:8080/user
Request Body
{
"id": "5d1c88a45ed21a532cb07a46",
"name":"Soumitra Roy",
"email":"contact@roytuts.com",
"pwd":"pwd"
}
Response – User successfully updated
Verifying Update
Request Method – GET
Request URL – http://localhost:8080/user
Response
Array[1]
0: {
"id": "5d1c88a45ed21a532cb07a46",
"name": "Soumitra Roy",
"email": "contact@roytuts.com"
}
]
Deleting User
Request Method – DELETE
Request URL – http://localhost:8080/user
Request Body
{
"id": "5d1c88a45ed21a532cb07a46"
}
Response – User successfully deleted
That’s all. Hope you got idea on Spring Boot MongoDB CRUD Example.
You may also like to read Python Flask REST API MongoDB CRUD Example.
Source Code
Thanks for reading.