Using MongoDB with Spring Boot

Spring Boot is a powerful framework for building microservices. It comes ready to work with almost every type of database, including the newer NoSQL variety. This guide shows you how to quickly integrate MongoDB with your Spring Boot Application


Dependency

Spring Boot has hundreds of starter packages that allow you to avoid writing code. They have a starter for mongodb as well. Include the following dependency:

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

Configuration

Add your database connection string in the your configuration file:

spring.data.mongodb.uri= mongodb://localhost:27017/mongodb

Model

Setup your entity model, just like you would for a traditional SQL entity


@Entity
@Data
public class Permit {
    @Id
    public String id;
    public String permitNum;
    public String revisionNum;
    public String permitType;
    public String structureType;
    public String work;
    public String streetNum;
    public String streetName;
    public String streetType;
    public String streetDirection;
    public String postal;
}

Setup Repository


public interface PermitRepository extends MongoRepository {
    List findAll();
}

That’s it! you can start using your Model to GET or POST data from your MongoDB Database

Author: Dev

Full Stack Developer at one of the largest Banks in Canada.