INTRODUCTION
NoSQL (Abbreviation of “Not only SQL”) means the databases that provides CRUD operations of the data whose structure is different than tabular relations which is used on relational databases. Nowadays more and more applications are starting to use NoSQL. In this article I will mention about NoSQL, then I will explain MongoDB with example Java codes for Sprint Boot integration in detail.
CONTENTS
1. NoSQL
____1.1 Comparison of SQL and NoSQL
____1.2 Pros and Cons of using NoSQL
2. MongoDB
____2.1 Overview
____2.2 Installation
____2.3 Data Modelling
____2.4 Data types
____2.5 Database
3.Example Java Project for MongoDB
____3.1 Maven Dependency and application.properties
____3.2 Entity
____3.3 Repository
____3.4 Service
____3.5 Controller
____3.6 Testing with Postman
________3.6.1 Create
________3.6.2 Update
________3.6.3 Read
________3.6.4 Delete
4.Conclusion
5.References
1. NoSQL
1.1 Comparison of SQL and NoSQL
- SQL DBs store the data as tables with fixed rows and columns.
- SQL DBs have rigid schemas.
- SQL DBs scales vertically.
- Examples: Oracle, Microsoft SQL Server, MySQL, PostgreSQL.
—
- NoSQL DBs store the data as JSON documents, key-value pairs, table with rows and dynamic columns or graph with nodes and edges.
- NoSQL DBs have flexible schemas
- NoSQL DBs scales horizontally.
- Examples: MongoDB, DynamoDB, Cassandra
1.2 Pros and Cons of using NoSQL
NoSQL databases provide several advantages when compared with SQL Databases. Some of them are:
- Flexible data model
NoSQL databases mostly have greatly flexible schemas. Whenever the requirements change for the database, it can be simply done thanks to the flexible schemas. - Horizontal scaling
When the capacity of an SQL database is exceeded, it is needed to scale vertically (switching to more powerful server). On the other hand, it is possible to scale horizontally for many NoSQL databases. - Fast queries
NoSQL queries can be faster when compared with SQL queries. The reason behind this is, SQL Databases are normalized most of the time which means queries for an entity needs joins on several tables. As the size of the tables grows, the joins can be expensive. On the other hand, NoSQL Databases stores the data as optimized for queries in most of the cases. - Easy for developers
The data structures of some NoSQL databases like MongoDB are mapped to popular programming languages. This feature makes it possible to store the data in the same way they are written in the code. Therefore, this leads to less code, faster development time and fewer bugs.
Nevertheless, they have some drawbacks. Some of them are:
- ACID support
The most mentioned drawback of NoSQL databases is that they do not have support for ACID (atomicity, consistency, isolation, durability) transactions across multiple documents. - Database size
NoSQL databases are mostly optimized for the queries but not for reducing data duplication. This may cause a larger storage size than SQL databases.
2.MongoDB
MongoDB is a cross-platform, document-oriented NoSQL database which has high performance, high availability, and easy scalability.
2.1 Overview
Database: Database is a physical container for collections.
Collection: Collection is a set of MongoDB documents. A collection exists within a single database. Collections do not require a schema. Documents in a collection can have different fields.
Document: A document is group of key-value pairs. They have dynamic schema, in other words the documents in a collection do not require to have the same fields. Also, common fields in the documents in a collection can have different types of data.
2.2 Installation
MongoDB can be installed on different platforms. On this article MongoDB will be used on Windows. The instructions of the installation can be found on: https://docs.mongodb.com/manual/tutorial/install-mongodb-on-windows/
2.4 Data types
String − Sequence of characters (It must be UTF-8 valid)
Integer − Numerical value (32 bit or 64 bit depending on the server)
Boolean − Boolean value (true/false)
Double − Floating point numerical value
Min/ Max keys − Used on comparing a value against the lowest and highest BSON elements
Arrays − Arrays, lists or several values under a single key
Timestamp − Timestamp
Object − Used on embedded documents
Null − Null value
Symbol − Identical to a string; however, generally reserved for languages that use a specific symbol type
Date − Current date and time as UNIX-Time format
Object ID − Document’s ID.
Binary data − Data in binary format
Code − JavaScript code
Regular expression − Regular expression data
2.5 Database operations
Create-Drop Database:
use <DATABASE_NAME>
creates the database with the given name if it does not exist, if it exists it returns(selects) the database.
db.dropDatabase()
removes the currently selected database.
Create-Drop Collection:
db.createCollection(<NAME>, <OPTIONS>)
creates a collection, where name is the name of the collection to be created and options are some optional parameters
db.<COLLECTION_NAME>.drop()
removes the specified collection from the selected database.
CRUD Operations of Document:
Create:
Both db.<COLLECTION_NAME>.save(<DOCUMENT>)
ordb.<COLLECTION_NAME>.insert(<DOCUMENT>)
creates the document when the field _id is not specified. When id is specified, save method does an upsert but insert method does only insert when there is no document with the given id, if there is an existing document with the given id the insert method throws an exception.
Read:
To find a document db.<COLLECTION_NAME>.find()
can be used which finds all the documents within the specified collection.
To filter the results, additional parameters to find method should be given. For example:
db.testCollection.find({"name":"MongoDB"})
finds the documents which has the name field equal to “MongoDB”
AND, OR and NOT cases are done with $and, $or and $not keywords respectively. For example:
db.testCollection.find({$or:[{"name":"MongoDB"}, {"surname":"NoSQL"}]})
Update:
To update a document, both save and update method can be used. Save method replaces the document with the given document; on the other hand, update method updates only the given fields.
The methods are used in this way:
db.<COLLECTION_NAME>.update(<SELECTION_CRITERIA>, <UPDATED_DATA>)db.<COLLECTION_NAME>.save({_id:ObjectId(<DOCUMENT_ID>),<NEW_DATA>})
Delete:
To delete the document, remove method can be used:
db.<COLLECTION_NAME>.remove(<DELETION_CRITTERIA>)
An example would be:
db.testCollection.remove({"name":"MongoDB"})
This deletes all the document that has name field equal to “MongoDB”. If no deletion criteria is provided, remove method deletes all the documents in the collection.
3.Example Java Project for MongoDB
MongoDB can easily be used in Sprint Boot projects. To demonstrate this, an example project is created. The example project is a simple MVC application that maintains the fitness progress of a person.
3.1 Maven dependency and application.properties
Firstly, MongoDB spring boot dependency should be added to pom.xml:
Then in application.properties file, the database connection info should be defined:
3.2 Entity
After that the entities can be created:
“@Document” marks the class as MongoDB Document model. The parameter “collection” can be defined within this annotation, if left empty the name of the class will be used as the name of the collection.
“@Id” defines the field that will be id of the document.
3.3 Repository
Sprint repository provides most of the functionalities for MongoDB in Java. But the repository should implement MongoRepository instead of JpaRepository or CrudRepository:
Other methods of repository are also available such as save and delete:
3.4 Service
If further complex logic is needed, custom methods can also be used, like for example:
3.5 Controller
All these functionalities in the example project is implemented as REST webservices to test them:
3.6 Testing with Postman
To test the example project, postman and MongoDB Compass (MongoDB GUI) are used.
3.6.1 Create
Initially there is no database as “exerciseApp”:
Then a POST request is sent to ExerciseApp:
As a result, the document is inserted to the collection:
3.6.2 Update
Let’s assume that an update on the previously inserted document is needed, like for example changing the exercise type from rowing to swimming.
A PUT request is sent to example project:
This updates the existing document, as it can be seen below:
3.6.3 Read
To demonstrate the read function, lets create another document:
As a result, there is 2 documents in the collection:
Firstly, let’s try the endpoint that calls the findBy method of repository:
The endpoint that calls the custom find method is also available to test on postman:
3.6.4 Delete
Assume that the document that has exercise type swimming are created by mistake. That document can be deleted by using its id field:
Hence, only one document in the collection should remain:
4.Conclusion
NoSQL Databases are non-tabular and store the data in a different way when compared with relational databases. It has various advantages over relational databases, such as horizontal scaling and flexible schemas. Also, MongoDB can be integrated to a Spring Boot project without so much effort.
The example project can be found on: https://github.com/unl40/ExerciseApp-Example-MongoDB-project
5.References
https://en.wikipedia.org/wiki/NoSQL
https://www.mongodb.com/nosql-explained/nosql-vs-sql
https://www.mongodb.com/nosql-explained
https://docs.mongodb.com/manual/tutorial/install-mongodb-on-windows/
https://www.tutorialspoint.com/mongodb/index.htm
https://docs.mongodb.com/manual/reference/method/#collection
https://www.w3schools.in/mongodb/data-types/
https://company-30077.frontify.com/d/ghqwg6pjpJrq/mongodb-identity#/basics/logo/logo-downloads-rgb