Spring Boot & MongoDB

MongoDB as the most popular NoSQL database is a source-available cross-platform document-oriented database program. It uses JSON-like documents with optional schemas and it is popular because of the ease with which data can be stored and retrieved.

MongoDB Introduction

MongoDB uses documents that contain a data structure composed of field and value pairs to store data so Documents are the basic unit of data in MongoDB. The documents are similar to JavaScript Object Notation, but use a variant called Binary JSON (BSON). BSON helps to have more data types and that is why MongoDB uses it. The overall terminology in MongoDB and RDBMS are similar and there are some small differences.

Database

The database is the container for collections. It has its own sets of files on the file system and a single MongoDB instance can have multiple databases.

Collection

MongoDB stores documents in collections. Collections are analogous to tables in relational databases. One of the benefits of collection compared to tables is that they do not enforce a schema and Documents within a collection can have different fields.

Document

Documents in MongoDB are equivalent to the rows in relational databases. Data is stored inside the documents in a set of key-value pairs and documents have a dynamic schema.

Join

Similar to join statement on RDBMS databases MongoDB has a similar concept that is used to related documents and joined them. Embedded documents help to mimic the join statement.

Getting Start

The MongoDB installation process is pretty straightforward on both windows and Linux. you just need to download the proper version and use the installer to have it installed. There are different MongoDB clients that you can use to create your database and explore data like MongoDB Compass, Robo 3T, nosqlbooster.

Thanks to the Spring Data the integration process between a Spring Boot application and MongoDB is pretty easy. To start you will need the following starter dependency on your pom file.

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

This dependency just like other starter dependencies will help you to have the basic configuration for required libraries all sorted out for you.

To connect to the MongoDB database you need to provide the following information in your application properties file.

spring.data.mongodb.authentication-database=admin
spring.data.mongodb.username=lms
spring.data.mongodb.password=password
spring.data.mongodb.database=school
spring.data.mongodb.port=27017
spring.data.mongodb.host=localhost

Another option is to provide this information as part of the connection URI if you are using Mongo 3.0 Java driver.

spring.data.mongodb.uri=mongodb://<username>:<pwd>@<host:port>/<dbname>

Records are stored in MongoDB in Documents in JSON-like format. To have an object map to a document schema in MongoDB you can use @Document annotation. the value that is passed to the annotation is the collection name in the MongoDB database.

@Document("student")
public class Student {
@Id
private String id;
private String name;
}

For example, the Student class with the given student collection will store in the document as follow:

{  
"_id": "1",
"name": "John",
"_class": "fp.spring.mongodb.model.Student"
}

Having all your documents ready to go you have multiple options to work with data on MongoDB. the most common ones are Mongo Template or Spring Data Repository.

1. Spring Data Repository

This approach is utilizing the standard Spring Data Repository to get the data which is similar to Data Repositories that are used to retrieve data from Relational Databases. Compared to MongoTemplate this method is more flexible and can be adapted based on your requirements.

public interface StudentRepository extends MongoRepository<Student, String> {

@Query("{name:'?0'}")
Optional<Student> findItemByName(String name);

}

MongoRepository will provide by default some methods for you to work with data like default CRUD operations. You can use them to add, update, delete and retrieve documents from MongoDB. To understand the query that you can use and the equivalent SQL statement you can refer to this link.

@Autowired
StudentRepository studentRepository;
...
// Get Student by Id
Optional<Student> studentOptional = studentRepository.findById(id);
// Search Student by name
Optional<Student> studentOptional = studentRepository.findItemByName(name);
// Add Student
studentRepository
.save(student);

As you can see in the above example we are using default and also custom methods added to our repository to add and search for documents. (Complete Code in GitHub)

2. MongoTemplate

Using standard template pattern in Spring and providing a simple and ready-to-use solution to work with data in MongoDB. By Injecting MongoTemplate you can use predefined methods to add, update, and retrieve data and you also have the option to create your custom query with Criteria and apply it to search data based on those criteria.

@Autowired
MongoTemplate mongoTemplate;
...
// Get Teacher by Id
Teacher teacher = mongoTemplate.findById(id,Teacher.class);
// Search Teacher by name
Teacher teacher= mongoTemplate.findOne(Query.query(Criteria.where("name").is(name)), Teacher.class);
// Save the teacher document
mongoTemplate.save(teacher);

Methods like find and findOne give you the flexibility to retrieve documents easily. (Complete Code in GitHub).

You can find the complete sample for this project on GitHub.

Hope this article helped you and please support me with your applauding 👏 for the story. if you don’t know how it is just like this:

Or buy me a coffee here!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Farzin Pashaee

Farzin Pashaee

Software Engineer at Maybank, AI and ML enthusiastic