"Welcome To Ashok IT"
"Spring Boot and MicroServices"
Topic : Spring Data JPA - NoSQL Database
Date : 26/10/2024
(Session - 54)
_____________________________________________________________________________________________________________________________
Today Session : Working with No SQL Database
============================================
* By using Spring Data Module we can communicate with any Database software.
* By using Spring Data JPA module we can communicate with any RDBMS Database Software(Oracle,MySQL,Postgresql,SQLServer etc.,)
* Inorder to communicate with No SQL Database's in Spring Data Module has given seperate modules for each NO SQL Database.
Mongo DB >>>>>>>>>>>> Spring Data MongoDB
Cassendar >>>>>>>>>>>> Spring Data for Apache Cassendar
Neo4J >>>>>>>>>>>> Spring Data for Neo4j
Redis >>>>>>>>>>>> Spring Data for Redis
* In RDBMS Database softwares always data will be stored in the form of "Tables(Rows & Columns)".
In No-SQL Database softwares the data will be stored in the form of Key-value based,document based,graph based.
* If data having fixed format and schema then we need go for SQL Databases.
If data is dynamically growing and no fixed format then we need go for No-SQL Databases.
Mongo DB
========
* Mongo DB is an open source and document orientied no-sql database software.
* Mongo DB Internally stores the data in the form of JSON i.e.,"documents".
* JSON >>>>> Javascript Object Notation
* JSON is format defining text-data as key-value pairs.
* JSON is an alternative for XML.
* XML based approach required more decoration for elements when compared to JSON data.
Example
=======
Customer c = new Customer();
c.setCustomerId(123);
c.setCustomerName("Mahesh");
c.setCustomerLocation("Hyderabad");
XML Format
==========
123
Mahesh
Hyderabad
JSON Format
===========
{
"customerId" : 123,
"customerName" : "mahesh",
"customerLocation" : "Hyderabad"
}
Multiple Customers
==================
123
Mahesh
Hyderabad
456
Ashok
Hyderabad
Multiple Customers
==================
[
{
"customerId" : 123,
"customerName" : "mahesh",
"customerLocation" : "Hyderabad"
},
{
"customerId" : 456,
"customerName" : "Ashok",
"customerLocation" : "Hyderabad"
}
]
Terminlogies
============
* SQL Database >>>>>>>>>> We are creating the logical databases per user
Mongo DB No SQL Database >>>>>>>> We will logical databases Ex: ashokit
* SQL Database >>>>>>>>>>>>>>>>>> Table
Mongo DB No-SQL Database >>>>>>>>>>>>> Collection Ex: customer,employee,user,login etc.,
* SQL Database >>>>>>>>>>>>>>>> Table(Row & columnns)
Mongo-DB No-SQL Databases >>>>>>>>>>>> Collection(documents1,document2......documentn);
Collection maintains documents (equal to records in SQL Database)
Mongo DB Environmental Setup
============================
1) Downloading the mongodb in below url
https://www.mongodb.com/try/download/community
current version of MongoDB : 8.0.1
2) Complete the installation process for MongoDB just like other windows software installation.
During the installation mongo DB remember the below points.
setup type >>>>> Click on "Complete" button.
Ensure the following checkbox is checked or not i.e., Install Mongod as a service.
Ensure the following checkbox is checked or not i.e., Install MongoDB Compass
Finally click on "Finish" Button.
3) Now we need to install the MongoDB Shell
* Download the MongoDB Shell seperately for following url i.e.,https://www.mongodb.com/try/download/shell
Current Version : 2.3.2
Platform : Windows 64-bit
Package : Zip File.
* After downloading the above zip file need to extract the zip folder and paste into operating system directory.
4) Adding path variables for MongoDB Software in Environmental variables section
MongoDB Server Location
=======================
C:\Program Files\MongoDB\Server\8.0\bin
MongoDB Shell Location
======================
C:\mongosh-2.3.2\bin
5) Goto Start Menu >>>> Search For Word as "Edit Environmental" and select this option >>> Environmental Variables Dialog will open and find "path" variable under "System Variables" and then click on "Edit" button.
* Click on "New" Button under "Edit Environmental Variable" and add the MongoDB Server & MongoDB Shell Location and
Click on "Ok" Button >> Again Click on "Ok" button.
C:\Program Files\MongoDB\Server\6.0\bin
C:\mongosh-1.10.6-win32-x64\mongosh-1.10.6-win32-x64\bin
6) After adding path variables Switch to "Cmd" prompt and test the below Command
C:\Users\NEW>mongod -version
OUTPUT
======
db version v8.0.1
Build Info: {
"version": "8.0.1",
"gitVersion": "fcbe67d668fff5a370e2d87b9b1f74bc11bb7b94",
"modules": [],
"allocator": "tcmalloc-gperf",
"environment": {
"distmod": "windows",
"distarch": "x86_64",
"target_arch": "x86_64"
}
}
If you see the above message so that MongoDB got Installed Successfully in our Machine.
Interacting with MongoDB Database
=================================
* There are two ways to interact with MongoDB
1) MongoDB Shell i.e., CLI Interface
2) MongoDB GUI Interface i.e.,MongoDB Compass,Robo3T,Studio3T etc.,
MongoDB Shell
=============
1) Open the MongoDB Shell with following location i.e.,C:\mongosh-2.3.2-win32-x64\bin\mongosh.exe
2) Onces Shell got opened the following message will appear i.e.,
Please enter a MongoDB connection string (Default: mongodb://localhost/): (Hit the Enter Key) and will get prompt below
SQL >>>>>>>>> Tables >>>>>>>>>>>>>>>>>>>>>>>> Collections
SQL >>>>>>>>> Rows representing Records >>>>>>>>>>>>>>>>>>>>Documents >>>>>> JSON
Get the List of Databases available in MongoDB
==============================================
test> show databases
(or)
test> show dbs
OUTPUT
======
admin 40.00 KiB
config 108.00 KiB
local 40.00 KiB
Creating our own Database in MonogoDB
=====================================
test> use ashokit
OUTPUT
======
switched to db ashokit
Getting Know about Current Database Name
========================================
ashokit> db
OUTPUT
======
ashokit
Listing the Databases
=====================
test> show dbs >>>>>>>> Untill create the collection the database name willn't appear in the list.
OUTPUT
======
admin 40.00 KiB
config 108.00 KiB
local 40.00 KiB
Creating Collection in MongoDB
===============================
ashokit> db.createCollection("students");
OUTPUT
======
{ ok: 1 }
Listing the Databases
=====================
ashokit> show dbs
OUTPUT
======
admin 40.00 KiB
ashokit 8.00 KiB
config 108.00 KiB
local 40.00 KiB
List of Collections
===================
ashokit> show collections
OUTPUT
======
students
Inserting the Documents into Collection(Inserting the Records into Database table)
==================================================================================
* db.collection.insertOne(): inserts a single document into a collection. If the document does not specify an _id field, MongoDB adds the _id field with an ObjectId value to the new document. See Insert Behavior.
Example
=======
ashokit> db.students.insertOne({"rollno" :123,
"name":"Mahesh",
"emailIds": ["mahesh.ashokit@gmail.com","maheshashokit@gmail.com"],
"contactno":"123456789"});
OUTPUT
======
{
acknowledged: true,
insertedId: ObjectId("63d13f30bc659c6bfb4218dc")
}
* db.collection.insertMany(): can insert multiple documents into a collection. Pass an array of documents to the method. If the documents do not specify an _id field, MongoDB adds the _id field with an ObjectId value to each document. See
Insert Behavior.
Example
=======
ashokit> db.students.insertMany([
{
"rollno" :123,
"name":"Rajesh",
"emailIds": ["rajesh.ashokit@gmail.com","rajeshashokit@gmail.com"],
"contactno":"123456789",
"totalMarks":25,
"city":"Hyderabad"
},
{
"rollno" :456,
"name":"Suresh",
"emailIds": ["suresh.ashokit@gmail.com","sureshashokit@gmail.com"],
"contactno":"112158748",
"totalMarks":50,
"city":"Delhi"
},
{
"rollno" :789,
"name":"Ramesh",
"emailIds": ["ramesh.ashokit@gmail.com","rameshashokit@gmail.com"],
"contactno":"112158748",
"totalMarks":75,
"city":"Hyderabad"
}
]);
OUTPUT
======
{
acknowledged: true,
insertedIds: {
'0': ObjectId("63d141b7bc659c6bfb4218dd"),
'1': ObjectId("63d141b7bc659c6bfb4218de"),
'2': ObjectId("63d1d7a03a5448a0dc715334")
}
}
Get All the Documents from Collection
=====================================
ashokit>db.students.find()
(or)
ashokit>db.students.find().pretty();
(or)
ashokit>db.students.find({});
OUTPUT
======
[
{
_id: ObjectId("63d13f30bc659c6bfb4218dc"),
rollno: 123,
name: 'Mahesh',
emailIds: [ 'mahesh.ashokit@gmail.com', 'maheshashokit@gmail.com' ]
},
{
_id: ObjectId("63d141b7bc659c6bfb4218dd"),
rollno: 123,
name: 'Rajesh',
emailIds: [ 'rajesh.ashokit@gmail.com', 'rajeshashokit@gmail.com' ],
contactno: '123456789'
},
{
_id: ObjectId("63d141b7bc659c6bfb4218de"),
rollno: 456,
name: 'Suresh',
emailIds: [ 'suresh.ashokit@gmail.com', 'sureshashokit@gmail.com' ],
contactno: '112158748'
}
]
Getting Records based on name of students
=========================================
ashokit> db.students.find({"name" :"Mahesh"});
(or)
ashokit> db.students.find({name :"Mahesh"});
OUTPUT
======
[
{
_id: ObjectId("63d13f30bc659c6bfb4218dc"),
rollno: 123,
name: 'Mahesh',
emailIds: [ 'mahesh.ashokit@gmail.com', 'maheshashokit@gmail.com' ]
}
]
Getting Records based on in condition
=====================================
ashokit>db.students.find( { name: { $in: [ "Suresh", "Mahesh" ] } } )
OUTPUT
======
[
{
_id: ObjectId("63d13f30bc659c6bfb4218dc"),
rollno: 123,
name: 'Mahesh',
emailIds: [ 'mahesh.ashokit@gmail.com', 'maheshashokit@gmail.com' ]
},
{
_id: ObjectId("63d141b7bc659c6bfb4218de"),
rollno: 456,
name: 'Suresh',
emailIds: [ 'suresh.ashokit@gmail.com', 'sureshashokit@gmail.com' ],
contactno: '112158748'
}
]
Getting Records based on And & Or Condition
===========================================
ashokit> db.students.find( { city: "Hyderabad", totalMarks: { $gte: 25 } } )
OUTPUT
======
[
{
_id: ObjectId("63d146bdbc659c6bfb4218df"),
rollno: 123,
name: 'Rajesh',
emailIds: [ 'rajesh.ashokit@gmail.com', 'rajeshashokit@gmail.com' ],
contactno: '123456789',
totalMarks: 25,
city: 'Hyderabad'
},
{
_id: ObjectId("63d146bdbc659c6bfb4218e1"),
rollno: 789,
name: 'Ramesh',
emailIds: [ 'ramesh.ashokit@gmail.com', 'rameshashokit@gmail.com' ],
contactno: '112158748',
totalMarks: 75,
city: 'Hyderabad'
}
]
ashokit> db.students.find( {
name: "Rajesh",
$or: [ { "totalMarks": { $gte: 25 } }, { "city": "Hyderabad" } ]
} )
Updating single Document
========================
ashokit>db.students.updateOne( { name: "Rajesh" },
{
$set: {
city: "Non-Metro City Hyderabad",
totalMarks: 85
}
});
OUTPUT
======
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
Updating Multiple Documents
===========================
ashokit> db.students.updateMany(
{city: "Hyderabad"},
{
$set: {totalMarks: 95,city: "Chennai"}
}
);
OUTPUT
======
{
acknowledged: true,
insertedId: null,
matchedCount: 2,
modifiedCount: 2,
upsertedCount: 0
}
Deleting Single Document
========================
ashokit> db.students.deleteOne({city:"Delhi"});
OUTPUT
======
{ acknowledged: true, deletedCount: 1 }
Deleting Multiple Documents
===========================
ashokit> db.students.deleteMany( { totalMarks: 85})
OUTPUT
======
{ acknowledged: true, deletedCount: 3 }
Deleting all Documents from Collection
======================================
ashokit> db.students.deleteMany({})
droppping the collection
========================
ashokit>db.students.drop();
For More Information about MongoDB Shell Commands
=================================================
***********https://www.mongodb.com/docs/mongodb-shell/crud/*************************************
MongoDB Compass GUI
===================
1) Open MongoDB Compass Tool and connect to database using button as "Connect".
2) Onces Database got connected left hand side we have "Databases Explorer" panel we can find the Database as "ashokit".
If you wanted to create new database click on "+ icon" beside the Databases section.
3) After creating the Database we can create some collection by clicking "+ Icon" newly created database. i.e.,movies
4) After creating the Collection of "movies" we need to add Documents as to be followed below
First make sure right hand side layout should be set to "Json Layout"
Secondly need to click on "ADD Data" button and again select "Insert Document" option and try to insert some documents using below scripts
[
{
title: "The Favourite",
genres: [ "Drama", "History" ],
runtime: 121,
rated: "R",
year: 2018,
directors: [ "Yorgos Lanthimos" ],
cast: [ "Olivia Colman", "Emma Stone", "Rachel Weisz" ],
type: "movie"
},
{
title: "Jurassic World: Fallen Kingdom",
genres: [ "Action", "Sci-Fi" ],
runtime: 130,
rated: "PG-13",
year: 2018,
directors: [ "J. A. Bayona" ],
cast: [ "Chris Pratt", "Bryce Dallas Howard", "Rafe Spall" ],
type: "movie"
},
{
title: "Tag",
genres: [ "Comedy", "Action" ],
runtime: 105,
rated: "R",
year: 2018,
directors: [ "Jeff Tomsic" ],
cast: [ "Annabelle Wallis", "Jeremy Renner", "Jon Hamm" ],
type: "movie"
}
]
5) After adding the multiple records using the filter option for retreiving the records based on business operation from MongoDB.
6) We can use option of Replace & Delete icon for updating & Removing the Documents from collection.