Open In App

How to Connect MongoDB with Spring Boot?

Last Updated : 31 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In recent times MongoDB is the most used database in the software industry. It’s easy to use and learn This database stands on top of document databases it provides the scalability and flexibility that you want with the querying and indexing that you need. In this, we will explain how we connect MongoDB with Spring Boot. Before starting this Software must be installed in your System

  • Java
  • Any Spring Boot Supported IDE Like -: STS (Spring Tool Suite), IntelliJ IDE, etc.
  • MongoDB

Add these dependencies in your pom.xml file in dependencies.

XML




<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>


 

MongoDB Connection Properties:

There is some important parameter we need to know to connect the MongoDB server with Spring Boot.

  • Port (By Default Port – 27017)
  • Host (By Default Host – localhost)
  • Database Name 
  • Credential (Optional)

These parameters we need to set in application properties.

spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=demo
spring.data.mongodb.username=username_value  (optional)
spring.data.mongodb.password=password_value (optional)

or,

spring.data.mongodb.uri=mongodb://your_username:your_password@localhost:27017/demo

Note:

  • demo (Database Name)
  • By default, you can use like this (if there is no username and password set in your MongoDB) => “spring.data.mongodb.uri=mongodb://localhost:27017/demo”
  • By default, we do not need a user and password.

Example Project

For Example, we are using STS (Spring Tool Suite) IDE, and we have created a new Project and added these Spring Data MongoDB, and Spring web dependencies to our project.

 

Step 1: We will create the “User” class you can create a class with any name and define any variable and annotate with “@document” you can refer below image for better understanding please keep in mind that your class will be your document name (Table name) and the variable will be column name when it will create in your database.

Java




import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
  
@Document
public class User {
    @Id
    private String userId;
    private String name;
    private String rollNumber;
      
    public User(String name, String rollNumber) {
        super();
        this.name = name;
        this.rollNumber = rollNumber;
    }
    public String getUserId() {
        return userId;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getRollNumber() {
        return rollNumber;
    }
    public void setRollNumber(String rollNumber) {
        this.rollNumber = rollNumber;
    }
}


Step 2: We will create an Interface that will extend MongoRepository with the help of this interface we will perform CRUD (Create, Read, Update, Delete) operation in our database.

Note:

  • Please keep in mind if you want to create one or more document (Table) for that every document (Table) you need to define a new interface that will extend MongoRepository.
  • MongoRepository<User,String> here “User” is my class name and “String” is my ID data type that we already defined in the User class and annotated with “@Id”.

Java




import org.springframework.data.mongodb.repository.MongoRepository;
  
public interface UserRepository extends MongoRepository<User,String>{
  
}


Step 3: We will define important connection parameters for the MongoDB server.

Note: # means that line of code is commented.

XML




#spring.data.mongodb.host=localhost
#spring.data.mongodb.port=27017
#spring.data.mongodb.database=userDatabase
server.port=8081


Step 4: Now this is the final step in this step we will create the controller class from there we will perform CRUD operation in our database.

  • We annotate the controller class with @RestController.
  • We create an object of our repository and annotate it with @Autowired.

Java




import java.util.List;
  
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
  
@RestController
public class UserController {
      
    @Autowired 
    private UserRepository userRepo;
      
    // Save method is predefine method in Mongo Repository
    // with this method we will save user in our database
    @PostMapping("/addUser")
    public User addUser(@RequestBody User user) {
        return userRepo.save(user);
    }
      
    // findAll method is predefine method in Mongo Repository 
    // with this method we will all user that is save in our database
    @GetMapping("/getAllUser")
    public List<User> getAllUser(){
        return userRepo.findAll(); 
    }
}


For checking whether it’s working fine or not for that we are using Postman.

Note:  

  • We do not need to insert the user Id MongoDB automatically will create a unique id and insert it into our data.”
  • These “name” and “rollNumber” must be the same as your column name or you can say the same as the User Class variable name otherwise the value will not insert in your database by default null value will store in the database.

Output:

 

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads