GrabObject

Spring Boot MongoDB Database Example

Spring Boot made it easy to setup and configure projects, and develop applications, because spring boot takes care of adding dependent jars to projects and it provides default configuration.

In this tutorial, let’s see how to develop web application with MongoDB as database using spring boot by creating expense tracker web application which allows user to add, delete and view expenses. Expenses data is stored in MongoDB.

Setup

First create maven project in eclipse, for detailed steps for creating spring boot project, please see spring boot example.

Then add spring boot starters to pom. To include jars for spring mvc web application, we need to add spring-boot-starter-web starter and for including MongoDB dependencies, add spring-boot-starter-data-mongodb starter. Then do maven project update by right clicking project and clicking maven and project update.

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.zoftino.spring.boot.examples</groupId>
	<artifactId>mongo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>mongo</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.5.RELEASE</version>
	</parent>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

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

Entity

Let’s create entity class and define fields for capturing expense data. Let’s mark bill id with annotation ID.

import org.springframework.data.annotation.Id;

public class Bill {
	@Id
	private Long id;
	private String name;
	private String type;
	private Double amount;

	public Bill(Long id, String name, String type, Double amount) {
		this.id = id;
		this.name = name;
		this.type = type;
		this.amount = amount;
	}

	public Long getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public Double getAmount() {
		return amount;
	}

	public void setAmount(Double amount) {
		this.amount = amount;
	}

}

MongoDB Repository

It is easy to access MongoDB for read and write operation using spring data. Spring data defines MongoDB repository interface which you can extend to define find methods. Spring data generates code for saving, querying and deleting entity.

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

public interface MongoDbRepository extends MongoRepository<Bill, Long>{
	public List<Bill> findByType(String type);	
}

Controller

Let’s create a controller with add, find and delete expenses methods, map them to path and annotate the controller with @RestController. For enabling spring boot auto configuration, annotate the controller with @EnableAutoConfiguration annotation. Then define mongo repository type field in controller and annotate it with Autowired so spring will provide an instance of it and assign to it.

The mongoDB repository instance is used for inserting, reading, and deleting expenses data.

@RestController
@EnableAutoConfiguration
public class MongoApp 
{
	@Autowired
	private MongoDbRepository mongoDbRepository;
	
	private final Logger log = LoggerFactory.getLogger(this.getClass());
	
	public static void main(String[] args) {
		SpringApplication.run(MongoApp.class, args);

	}	
	@RequestMapping(value="/")
	public String home() {
		StringBuilder sb = new StringBuilder();
		sb.append("add bill url : /add/billId/name/type/amount");
		sb.append("\n");
		sb.append("delete bill url : /delete/billId");
		sb.append("\n");
		sb.append("get bill url : /get/billId");
		sb.append("\n");
		sb.append("get bills by type url : /getByType/type");
		sb.append("\n");
		return sb.toString();
	}	
	@RequestMapping(value="/add/{id}/{name}/{type}/{amount}")
	public String addBill(@PathVariable Long id, @PathVariable String name, 
			@PathVariable String type, @PathVariable double amount) {
		log.info("insert bill");
		mongoDbRepository.save(new Bill(id, name, type, amount));
		return "bill inserted";
	}	
	@RequestMapping(value="/getByType/{type}")
	public List<Bill> getBillsByType(@PathVariable String type) {
		log.info("get bills");		
		return mongoDbRepository.findByType(type);
	}
	@RequestMapping(value="/get/{id}")
	public Optional<Bill> getBill(@PathVariable Long id) {
		log.info("get bills by type");
		return mongoDbRepository.findById(id);
	}
	@RequestMapping(value="/delete/{id}")
	public String deleteBill(@PathVariable Long id) {
		log.info("delete bill");
		mongoDbRepository.deleteById(id);
		return "bill deleted";
	}
}

Project Structure

spring boot MongoDB example project

MongoDB Setup

For testing the application, we need MongoDB database. Let’s use free tier MongoDB database on cloud for testing our application. For detailed steps on how to use MongoDB on cloud, please see connecting to MongoDB database on cloud from applications tutorial.

MongoDB URL

If you install and start MongoDB on your local machine, you don’t need to add any configuration in order for the app to connect to MongoDB as spring boot provides default configuration.

But to inform spring boot to connect to MongoDB on cloud, we need to add connection string to configuration. After you setup MongoDB on cloud and get connection string, place it in application.properties file sand save it under src/main/resources folder. The property that needs be used for this is spring.data.mongodb.uri.

spring.data.mongodb.uri=mongodb+srv://myuserid:mypasswd@cluster0-1uosh.mongodb.net/test

Testing

Start the application by running the main method in controller, it will start the embedded tomcat server and deploy the web app. Access the application from browser to add, find and delete expenses.

spring boot mongo database examplespring boot mongo database query example