You are here
Home > Spring Boot >

Spring Boot MongoDB Java Tutorial With Examples

Spring Boot MongoDB Java TutorialAs a Java developer, we can’t develop an insightful application without the use of a database software. Traditionally, we use a relational database to work with an application. Of course, A relational database is a structured database and contains multiple tables to maintain meaningful relations between them. Additionally, it uses SQL like queries to operate with data stored in the tables.

In contrast, suppose we have to work with a large amount of unstructured data which is not beneficial to store in the form of tables, keeping other factors in mind as well, then how will we store our data? The simple answer is ‘we should use MongoDB’ in that case. Further, you might even have some other questions in your mind. Of course, our topic on ‘Spring Boot MongoDB Java Tutorial’ will answer all your questions.

In order to confidently work on MongoDB, you just need to go through this article step by step. Let’s start learning a new hot topic ‘Spring Boot MongoDB Java Tutorial’ accordingly.

What will you learn from this Topic?

1) What is MongoDB ? Why do we need it ?

2) What is a NoSQL DB with examples of some popular NoSQL Databases?

3) Equally important, What are the benefits and drawbacks of using a NoSQL database?

4) What are the key features of MongoDB?

5) In addition, How to install MongoDB on your system?

6) How to do basic operations in MongoDB collections like insert, retrieve, update, delete ?

7) Finally, How to use MongoDB in a Spring Boot Application with step by step process ?

8) Also, How to use annotation @Document and other annotations ?

9) Last but not the least you will learn ‘How to work in Spring Boot with MongoDB?’ under Spring Boot MongoDB Java Tutorial.

What is Mongo DB ?

How to work with MongoDB in Spring Boot Project?Needless to say, ‘What is Mongo DB’ is equally important as ‘How to work with MongoDB’ is. Undoubtedly, Mongo DB is a NoSQL database. It stores data in collection format. Each Collection stores data in document format. Additionally, Each document is similar to a JSON Object. To make it simple to understand, consider Collection as a table in SQL DB and document as a row. We also call MongoDB as a document-oriented database. It means you can store your records without worrying about the type of fields and number of fields. However, MongoDB doesn’t support advanced analytics and joins like SQL DB. In summary, It just stores unstructured data in JSON format.

Every JSON document is identified by an ID(_id) which is in hexadecimal by default. This ID (primary key) is auto-generated by MongoDB only. Furthermore, We can even modify this ID. We retrieved below student data from MongoDB which is in JSON format as shown below. As shown in the first student data, auto-generated id is represented by [“_id” : ObjectId(“5f8ff72f5b175156a2ba3c3d”)] whereas in remaining three students we have modified value of _id attribute. Additionally, one _class attribute will be autogenerated which represents the package name of the entity.

We can see a clear difference between a SQL DB and Mongo DB from the pictorial representation in the screenshot. Programmatically, we replace @Entity with @Document in case of Mongo DB. Furthermore, instead of tabular format of data in SQL DB, Mongo DB represents data in JSON format.

One object in Java is equivalent to one JSON document in MongoDB. For example, below JSON format code represents data in Mongo DB.

Student data in Mongo DB
> db.student.find().pretty()

"_id" : ObjectId("5f8ff72f5b175156a2ba3c3d"),
"stdId" : 5001,
"stdName" : "George",
"stdFee" : 2740,
"_class" : ""
"_id" : "A10102B54DEF",
"stdId" : 5002,
"stdName" : "Victoria",
"stdFee" : 2795,
"_class" : ""
"_id" : "A10102B54DE0",
"stdId" : 5003,
"stdName" : "Mary",
"stdFee" : 2999,
"_class" : ""
"_id" : "dc35e897456",
"stdId" : 5004,
"stdName" : "David",
"stdFee" : 2910,
"_class" : ""

What is NoSQL DB ? What are some popular examples of NoSQL databases?

NoSQL databases are those who store data in a format other than relational tables. These databases can store relational data, but they just store it differently than relational databases do.  Some examples of popular NoSQL databases are MongoDB, CouchDB, CouchBase, Cassandra, HBase, Redis, Riak, Neo4J. MongoDB, CouchDB, CouchBase are document-oriented NoSQL databases, Redis and Riak are key-value stores, Cassandra and HBase are column family stores and Neo4J is a graph database.

SQL data models allow relations by joining tables. On the other hand, NoSQL data models allow related data to be nested within a single data structure. Some people in the industry say the term “NoSQL” stands for “non SQL” while others say it stands for “not only SQL.”

If you want to learn more on NoSQL databases and have a good understanding of them, kindly visit a separate article on ‘All About NoSQL Databases‘ .

What are the benefits of using a NoSQL Database?

NoSQL databases are more flexible and scalable, faster, reliable, distributed, schema-free architecture, easy replication support, simple API, support for big data etc. NoSQL databases can often perform better than SQL(relational databases) for your use case. For example, if you’re using a document database and are storing all the information about an object in the same document (so that it matches the objects in your code), the database only needs to go to one place for those queries. In a SQL database, the same query would likely involve joining multiple tables and records, which can dramatically impact performance while also slowing down how quickly developers write code.

What are the Drawbacks of a NoSQL Database?

One of the recognized drawbacks of NoSQL databases is that they don’t support ACID (atomicity, consistency, isolation, durability) transactions across multiple documents. Single record atomicity is possible for lots of applications with appropriate schema design. However, there are still many applications that may demand ACID across multiple records. Further, MongoDB included support for multi-document ACID transactions in the 4.0 release to address this drawback. As NoSQL data models primarily focused on optimizing for queries rather than reducing data duplication, therefore NoSQL databases can be larger than SQL databases.

Key features of MongoDB

Document-Oriented: MongoDB stores data in documents, which are JSON-like data structures that can fluctuate in structure from one document to another. This allows developers to store complex, hierarchical data without ordering it into tables and rows.

Scalability: MongoDB is designed to scale horizontally across multiple servers, which provides high availability and scalability. It supports sharding, which involves distributing data across multiple servers to handle larger volumes of data and high performance.

Indexes: MongoDB supports various types of indexes, including single-field, compound, and multi-key indexes, which can improve query performance and ensure effective data retrieval.

Aggregation Framework: MongoDB’s aggregation framework provides powerful tools for performing complex data aggregation and analysis operations. It allows developers to perform tasks such as filtering, grouping, sorting, and transforming data in real-time.

How to download & install MongoDB in your system?

In order to work with MongoDB, make sure that you have installed the Mongo DB in your system. If not, please visit our article on how to download and install MongoDB in your system. Here, you will find step by step tutorial to download & install MongoDB including some required commands to operate on it.

How to create collections, insert, retrieve, update & delete records in MongoDB ?

First Start MongoDB server then start MongoDB client by typing below commands on two separate command prompts respectively.
->Start Mongo Server : cmd > mongodb
->Start Mongo Client  : cmd > mongo

Now practice running below commands on MongoDB client window to get confidence on this.

1) View all existing Databases : > show dbs

2) View current current Database : > db

3) Create your own Database : > use <DATABASE_NAME>
MongoDB use DATABASE_NAME is used to create database. The command will create a new database if it doesn’t exist, otherwise it will return the existing database.
example :
> use myTestDB

4) View all existing collections : > show collections

5) Create a collection and insert data into it
> db.<COLLECTION_NAME>.insert({key:value….})
example :
> db.employee.insert({“eid”:137229, “ename”:”Anderson”, “esal” :96784})

6) Display all Documents(JSON) from a collection
> db.<COLLECTION_NAME>.find()
> db.<COLLECTION_NAME>.find().pretty() [pretty() method displays the results in a formatted way ]
example :
> db.employee.find({“ename”:”Anderson”}).pretty()

7) Delete Document (JSON) from a Collection
> db.<COLLECTION_NAME>.deleteOne({k:v})  [deletes one record]
> db.<COLLECTION_NAME>.deleteMany({k:v}) [deletes multiple records]
> db.employee.deleteOne({“ename”:”Anderson”})

8) Update document from a collection
> db.employee.update({‘ename’:’Anderson’},{$set:{‘ename’:’George’}})

9) Drop a Collection
> db.<COLLECTION_NAME>.drop()
> db.employee.drop()

10) Drop a database
Dropping database is a 2 step process. First use a database then drop it, otherwise it will delete default ‘test’ database.
> use myTestDB
> db.dropDatabase()

Spring Boot MongoDB Java Tutorial

In the above sections, we have learnt basics of NoSQL Databases followed by MongoDB and its installation. In the subsequent sections, we will discuss about Spring Boot with Java MongoDB.

How to work in Spring Boot with MongoDB?

Let’s create an example of Spring Boot test application using MongoDB step by step.

What all Tools & Technologies used in this example project?

♦ STS (Spring Tool Suite) : Version-> 4.7.1.RELEASE
⇒ Dependent Starters : ‘Spring Boot Mongodb’, and ‘Lombok’
♦ JDK8 or later versions (Extremely tested on JDK8, JDK11 and JDK14)
♥ MongoDB 3.6.20 2008R2Plus SSL (64 bit)

Create a Spring Boot Starter Project in STS(Spring Tool Suite)

While creating Starter Project select ‘Spring Data MongoDB’, and ‘Lombok’ as starter project dependencies. Still, if you don’t know how to create Spring Boot Starter Project, Kindly visit Internal Link. Also, if you are interested to know more about Lombok, please visit about Lombok. Additionally to know how to install MongoDB use this internal link.


Creating an Entity class

We are taking ‘’ as an entity to test the application. Here, observe the @Document annotation instead of @Entity.


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;

@Document // Maps Entity class objects to JSON formatted Documents
public class Book {

@Id // making this variable as ID, will be auto-generated by MongoDB
private String id;

private Integer bookId;
private String bookName;
private String bookAuthor;
private Double bookCost;

Creating Repository Interface

As per standard naming convention, Create interface which will extend from MongoRepository<Book, Integer>as below example code.



public interface BookRepository extends MongoRepository<Book, Integer> {


Creating Runner class

Create one runner class named as ‘’ just to test the application once. It implements ‘’. In this example we are saving 4 books in MongoDB. In addition, updating ID of last book manually(which is allowed) and the name of the author. MongoDB will consider this as a new record. At the last, retrieve all the saved books and display it in the console. For example, below is the code.

import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;


public class BookTestRunner implements CommandLineRunner {

private BookRepository bookRepo;

public void run(String... args) throws Exception {

// Removing old data if exists

// Saving 4 books into DB
new Book(501, "Core Java", "Kathy Sierra", 1065.5),
new Book(502, "Spring in Action", "Craig Walls", 940.75),
new Book(503, "Hibernate in Action", "Gavin King", 889.25),
new Book(504, "Practical MongoDB", "Shakuntala Gupta", 785.0)
System.out.println("All Data saved into MongoDB");

// Updating ID(PK) manually (allowed) : It will create one new record Book("ISBN10:1484240251", 504,"Practical MongoDB", "Navin Sabharwal", 785.0)); // insert

// Printing all books
List<Book> bookList = bookRepo.findAll();



Running the Application

Right click on the project, then select “Run As’ >> ‘Spring Boot App’.

Output from STS

On running as Spring Boot App, you will see the below output.

Output from STS console
All Data saved into MongoDB
Book(id=5fac078513a1bf3485c961a2, bookId=501, bookName=Core Java, bookAuthor=Kathy Sierra, bookCost=1065.5)
Book(id=5fac078513a1bf3485c961a3, bookId=502, bookName=Spring in Action, bookAuthor=Craig Walls, bookCost=940.75)
Book(id=5fac078513a1bf3485c961a4, bookId=503, bookName=Hibernate in Action, bookAuthor=Gavin King, bookCost=889.25)
Book(id=5fac078513a1bf3485c961a5, bookId=504, bookName=Practical MongoDB, bookAuthor=Shakuntala Gupta, bookCost=785.0)
Book(id=ISBN10:1484240251, bookId=504, bookName=Practical MongoDB, bookAuthor=Navin Sabharwal, bookCost=785.0)

Output from MongoDB

Run below command from MongoDB client and observe the output as below

Output from MongoDB
"_id" : ObjectId("5fabf2fa4008d81d97a94a83"),
"bookId" : 501,
"bookName" : "Core Java",
"bookAuthor" : "Kathy Sierra",
"bookCost" : 1065.5,
"_class" : ""
"_id" : ObjectId("5fabf2fa4008d81d97a94a84"),
"bookId" : 502,
"bookName" : "Spring in Action",
"bookAuthor" : "Craig Walls",
"bookCost" : 940.75,
"_class" : ""
"_id" : ObjectId("5fabf2fa4008d81d97a94a85"),
"bookId" : 503,
"bookName" : "Hibernate in Action",
"bookAuthor" : "Gavin King",
"bookCost" : 889.25,
"_class" : ""
"_id" : ObjectId("5fabf2fa4008d81d97a94a86"),
"bookId" : 504,
"bookName" : "Practical MongoDB",
"bookAuthor" : "Shakuntala Gupta",
"bookCost" : 785,
"_class" : ""
"_id" : "ISBN10:1484240251",
"bookId" : 504,
"bookName" : "Practical MongoDB",
"bookAuthor" : "Navin Sabharwal",
"bookCost" : 785,
"_class" : ""


Links to Other tutorials on MongoDB with Spring Boot

Below are the links to learn MongoDB in depth with Spring Boot.

Spring Boot MongoDB CRUD Example 
Spring Boot MongoDB @Query Examples 
Spring Boot MongoDB using MongoTemplate Examples including CRUD 


Is Spring Boot suitable for microservices architecture with MongoDB?

Yes, Spring Boot is well suitable for developing microservices, and when combined with MongoDB, it provides a flexible and scalable solution. Each microservice can independently connect to its MongoDB instance. However, Spring Boot’s modular design speeds up the development of microservices.

Why use MongoDB with Spring Boot?

MongoDB’s document-oriented data model and Spring Boot’s flexible architecture complement each other well. MongoDB’s scalability, high availability, and rich query language make it a natural choice for Spring Boot applications.

What are some best practices for using MongoDB with Spring Boot?

Some best practices include defining appropriate indexes for your queries, optimizing your data model for performance, using MongoDB’s aggregation framework for complex queries, and utilizing Spring Boot’s error handling and logging capabilities.

How do we handle data migration and schema changes in MongoDB with Spring Boot?

MongoDB’s dynamic schema and Spring Boot’s flexibility make it easy to handle data migration and schema changes. We can use tools like MongoDB Compass or Robo 3T to visualize our data and make schema modifications as needed. Additionally, Spring Boot’s auto-configuration and schema-less design make it easy to adapt to changing requirements without downtime.


Once you finish going through all the details of this topic ‘Spring Boot MongoDB Java Tutorial’, Of course, you will feel comfortable in working with MongoDB. Although, this topic was a foundation to the MongoDB. Further, in upcoming topics of MongoDB, we will learn more complex part of it with examples. We will update this topic as well whenever required to do so. Also, please feel free to provide your comments below.

4 thoughts on “Spring Boot MongoDB Java Tutorial With Examples

Leave a Reply