As 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 Tutorialโ will answer all your questions.
In order to start working on Mongo DB confidently, you just need to go through this article step by step. Letโs start learning a new hot topic โSpring Boot MongoDB Tutorialโ accordingly.
Table of Contents (Click on links below to navigate)
- 1 What will you learn from this Topic?
- 2 What is Mongo DB ?
- 3 What is NoSQL DB ? What are some popular examples of NoSQL databases?
- 4 How many types of NoSQL DB are there?
- 5 What are the benefits of using a NoSQL Database?
- 6 What are the Drawbacks of a NoSQL Database?
- 7 How to download & install MongoDB in your system?
- 8 How to create collections, insert, retrieve, update & delete records in MongoDB ?
- 9 How to work in Spring Boot with MongoDB?
- 9.1 What allย Tools & Technologies used in this example project?
- 9.2 Create a Spring Boot Starter Project in STS(Spring Tool Suite)
- 9.3 Updating application.properties
- 9.4 Creating an Entity class
- 9.5 Creating Repository Interface
- 9.6 Creating Runner class
- 9.7 Running the Application
- 9.8 Output from STS
- 9.9 Output from MongoDB
- 10 Links to Other tutorials on MongoDB with Spring Boot
- 11 Summary
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) Additionally, How many types of NoSQL databases are there with examples ?
4) Equally importantly, What are the benefits and drawbacks of using a NoSQL database?
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 Tutorial.
What is Mongo DB ?
Needless to say, โWhat is Mongo DBโ is equally important as โHow to work with MongoDB : A NoSQL Database?โ is. Undoubtedly, Mongo DB is a NoSQL database. Moreover, 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.
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โ .
How many types of NoSQL DB are there?
Key-Values Stores, Wide-column Stores, Document Databases, Graph Databases are the types of NoSQL Databases.
Key-Values Stores
The Key-Values Stores are simplest and easiest to implement. They internally use a hash table where there is a unique key and a pointer to a particular item of data. Key-value Stores are great for use cases where you need to store large amounts of data, but you donโt need to perform complex queries to retrieve it. Examples:ย Tokyo Cabinet/Tyrant, Redis, DynanoDB, Voldemort, Oracle BDB, Amazon SimpleDB, Riak.
Wide-column Stores
They store data in tables, rows, and dynamic columns. Here each row doesnโt need to have the same columns. Therefore, they are better in flexibility over relational databases. Also, these were created to store and process very large amounts of data distributed over many machines. Wide-column stores are suitable for storing Internet of Things data and user profile data. Examples:ย Cassandra, HBase
Document Databases
They are similar to key-value stores and inspired by Lotus Notes. Document Databases store data in documents like JSON objects. Further JSON can store values in a variety of types like Strings, Numbers, Booleans, Arrays or Objects. They also support powerful query languages. Hence, they can be used as a general purpose database. According to DB-engines ranking, MongoDB is consistently ranked as the worldโs most popular NoSQL database. Examples: MongoDB, CouchDB
Graph Databases
They use a flexible graph model which, again, can scale across multiple machines. Graph Databases store data in nodes and edges. Nodes typically store information about people, places, and things while edges store information about the relationships between the nodes. They are useful in use cases where you need to traverse relationships to look for patterns such as social networks, fraud detection, and recommendation engines. Examples:ย Neo4J, JanusGraph, InfoGrid, Infinite Graph
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.
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 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 > mongod
->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]
example:
> db.employee.deleteOne({โenameโ:โAndersonโ})
8) Update document from a collection
> db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)
> 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()
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 Boot 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.
Updating application.properties
Creating an Entity class
We are taking โBook.javaโ as an entity to test the application. Here, observe the @Document annotation instead of @Entity.
Creating Repository Interface
As per standard naming convention, Create interface BookRepository.java which will extend from MongoRepository<Book, Integer>as below example code.
Creating Runner class
Create one runner class named as โBookTestRunner.javaโ just to test the application once. It implements โCommandLineRunner.javaโ. 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.
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 MongoDB
Run below command from MongoDB client and observe the output as below
> db.book.find().pretty()
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
Summary
Once you finish going through all the details of this topic โSpring Boot MongoDB 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.
ย
send me your email
[email protected]