Connect MongoDB in Spring Boot: Maven & Gradle Configuration

MongoDB is a popular NoSQL database that provides flexibility and scalability for modern applications. When building Spring Boot applications, integrating MongoDB becomes essential for handling data storage and retrieval efficiently. In this blog, we will walk you through the process of connecting MongoDB with a Spring Boot application. By the end of this guide, you’ll have a clear understanding of how to set up the necessary dependencies and configuration to establish a seamless connection between Spring Boot and MongoDB.

Prerequisites:

Before we begin, make sure you have the following prerequisites in place:

  1. JDK 8 or higher installed on your system.
  2. A Spring Boot project setup using your preferred build tool (Maven or Gradle).
  3. MongoDB installed on your system

Note: For this tutorial, we are using our basic skeleton project for springboot. You can also download the project from here.

Step 1: Add MongoDB Dependency to Your Project

The first step is to add the MongoDB dependency to your Spring Boot project. Open your build configuration file (pom.xml for Maven or build.gradle for Gradle) and add the following dependency:

For Maven:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

For Gradle:

implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'

Save the file, and your project will now have the necessary MongoDB support.

Step 2: Configure MongoDB Connection Properties

Next, you need to configure the MongoDB connection properties in your Spring Boot application. In the application.properties (or application.yml) file, add the following lines:

For application.properties:

spring.data.mongodb.host=your_mongodb_host
spring.data.mongodb.port=your_mongodb_port
spring.data.mongodb.database=your_database_name

# Example
# spring.data.mongodb.host=localhost
# spring.data.mongodb.port=27017
# spring.data.mongodb.database=tutorial

For application.yml:

spring:
  data:
    mongodb:
      host: your_mongodb_host
      port: your_mongodb_port
      database: your_database_name

Replace your_mongodb_host, your_mongodb_port, and your_database_name with your MongoDB server details.

Step 2.1: Configuration For Secure MongoDB Setup

If you are getting this error: Command failed with error 13 (Unauthorized): ‘command find requires authentication’ on server localhost:27017.

The error message “Command failed with error 13 (Unauthorized): ‘command find requires authentication’ on server localhost:27017” indicates that the MongoDB server you are trying to connect to requires authentication, but your application is trying to execute a find (query) command without proper authentication credentials.

To resolve this issue, you need to provide the necessary authentication credentials to your Spring Boot application, allowing it to connect to the MongoDB server successfully. Here’s how you can do it:

Step 1: Create a MongoDB User with Required Privileges

First, you need to create a MongoDB user with the necessary privileges to perform CRUD operations on the database you want to access. You can do this using the MongoDB shell or a MongoDB administration tool.

  1. Open a terminal or command prompt.
  2. Connect to your MongoDB server using the MongoDB shell:
mongo -u admin
  1. Switch to the appropriate database:
use your_database_name
  1. Create a new user with the required privileges. Replace ‘your_username’ and ‘your_password’ with your desired username and password:
db.createUser(
   {
     user: "your_username",
     pwd: "your_password",
     roles: [ "readWrite", "dbAdmin" ]
   }
)

The ‘readWrite’ role allows the user to read and write data in the specified database, while the ‘dbAdmin’ role grants administrative privileges for the database.

Step 2 Update: MongoDB Connection Properties in Your Spring Boot Application

Now that you have created the MongoDB user, you need to update the connection properties in your Spring Boot application to include the authentication credentials.

In your application.properties (or application.yml) file, add the following lines:

For application.properties:

spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=your_database_name
spring.data.mongodb.username=your_username
spring.data.mongodb.password=your_password

For application.yml:

spring:
  data:
    mongodb:
      host: localhost
      port: 27017
      database: your_database_name
      username: your_username
      password: your_password

Make sure to replace ‘your_database_name’, ‘your_username’, and ‘your_password’ with the actual values you used while creating the MongoDB user.

Step 3: Create the Document Class

Next, create a Java class representing the document structure in MongoDB. In this example, we’ll create a simple Book class with basic attributes like id, title, author, and price.

// Book.java

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

@Document(collection = "books")
public class Book {
    @Id
    private String id;
    private String title;
    private String author;
    private double price;

    // Constructors, getters, setters (Omitted for brevity)
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}

Step 4: Create MongoDB Repository

Now, define a MongoDB repository to handle CRUD operations on the Book objects. We’ll use the MongoRepository interface provided by Spring Data MongoDB.

// BookRepository.java

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface BookRepository extends MongoRepository<Book, String> {
    // Additional custom queries can be defined here if needed
}

Step 5: Implement CRUD Operations

Next, let’s create a service class that uses the BookRepository to perform CRUD operations on the Book collection.

// BookService.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class BookService {
    private final BookRepository bookRepository;

    @Autowired
    public BookService(BookRepository bookRepository) {
        this.bookRepository = bookRepository;
    }

    public Book createBook(Book book) {
        return bookRepository.save(book);
    }

    public List<Book> getAllBooks() {
        return bookRepository.findAll();
    }

    public Optional<Book> getBookById(String id) {
        return bookRepository.findById(id);
    }

    public Book updateBook(Book book) {
        return bookRepository.save(book);
    }

    public void deleteBook(String id) {
        bookRepository.deleteById(id);
    }
}

Step 6: Create a REST Controller

Finally, create a REST controller that exposes endpoints for CRUD opperations using the BookService.

// BookController.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {
    private final BookService bookService;

    @Autowired
    public BookController(BookService bookService) {
        this.bookService = bookService;
    }

    @PostMapping
    public Book createBook(@RequestBody Book book) {
        return bookService.createBook(book);
    }

    @GetMapping
    public List<Book> getAllBooks() {
        return bookService.getAllBooks();
    }

    @GetMapping("/{id}")
    public Book getBookById(@PathVariable String id) {
        return bookService.getBookById(id).orElse(null);
    }

    @PutMapping("/{id}")
    public Book updateBook(@PathVariable String id, @RequestBody Book book) {
        book.setId(id);
        return bookService.updateBook(book);
    }

    @DeleteMapping("/{id}")
    public void deleteBook(@PathVariable String id) {
        bookService.deleteBook(id);
    }
}

Step 7: Run and Test the Application

Now, you have completed the setup. You can run your Spring Boot application. The application will start, and you should be able to access the REST endpoints defined in the BookController. For example you can test bellow using Postman:

  • To get all books: GET http://localhost:8080/books
  • To add a book: POST http://localhost:8080/books with a JSON body containing book details – { "title": "Example Book", "author": "John Doe", "price": 200.00 }
  • To delete all books: DELETE http://localhost:8080/books
  • To delete book by id: DELETE http://localhost:8080/books/{id}

Note: You can create your HTML Form, submitting and displaying data.

Conclusion:

In this blog, we have explained how to create a Springboot application that connects to MongoDB and performs CRUD operations on a Book collection. With the setup in place, you can easily add more complex queries and additional features to your application. Remember to haandle exceptions and implement proper validation in a real-world application. Happy coding!

Find this project on Github.

Also Read How to Protect Sensitive Data in a Java Project Like Spring Boot.

Read our Blog on How to Provide Initial Default Data for Models in Spring Boot