0% found this document useful (0 votes)
29 views20 pages

Mongo DB Notes by Tishant Agrawal

Uploaded by

cloudangelm2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views20 pages

Mongo DB Notes by Tishant Agrawal

Uploaded by

cloudangelm2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

introduction to nosql databases

NoSQL Database is used to refer a non-SQL or non relational database.

It provides a mechanism for storage and retrieval of data other than tabular
relations model used in relational databases. NoSQL database doesn't use
tables for storing data. It is generally used to store big data and real-time web
applications.

NoSQL is a type of database management system (DBMS) that is


designed to handle and store large volumes of unstructured and
semi-structured data.NoSQL databases use flexible data models that
can adapt to changes in data structures and are capable of scaling
horizontally to handle growing amounts of data.

○ It supports query language.

○ It provides fast performance.

○ It provides horizontal scalability.

NoSQL databases are generally classified into four main categories:

1. Document databases: These databases store data as

semi-structured documents, such as JSON or XML, and can be

queried using document-oriented query languages.

2. Key-value stores: These databases store data as key-value

pairs, and are optimized for simple and fast read/write

operations.

3. Column-family stores: These databases store data as column

families, which are sets of columns that are treated as a

single entity. They are optimized for fast and efficient

querying of large amounts of data.


4. Graph databases: These databases store data as nodes and

edges, and are designed to handle complex relationships

between data.

NoSQL databases are often used in applications where there is a

high volume of data that needs to be processed and analyzed in

real-time, such as social media analytics, e-commerce, and

gaming.

mongoDB

MongoDB is an open-source document-oriented database that is


designed to store a large scale of data and also allows you to work
with that data very efficiently. It is categorized under the NoSQL (Not
only SQL) database because the storage and retrieval of data in the
MongoDB are not in the form of tables.
The MongoDB database is developed and managed by MongoDB.Inc
under SSPL(Server Side Public License) and initially released in
February 2009. It also provides official driver support for all the
popular languages like C, C++, C#, and .Net, Go, Java, Node.js, Perl,
PHP, Python
its NoSQL database, the data is stored in the collections and
documents.
MongoDB is not based on the table-like relational database structure
but provides an altogether different mechanism for storage and
retrieval of data, that’s why known as NoSQL database. Here, the term
‘NoSQL’ means ‘non-relational’. The format of storage is called BSON (
similar to JSON format).

MongoDB work in two layers →

● Application Layer and

● Data layer
Application Layer is also known as the Final Abstraction Layer, it has
two-parts, first is a Frontend (User Interface) and the second is
Backend (server). The frontend is the place where the user uses
MongoDB with the help of a Web or Mobile. This web and mobile
include web pages, mobile applications, android default applications,
IOS applications, etc. The backend contains a server which is used to
perform server-side logic and also contain drivers or mongo shell to
interact with MongoDB server with the help of queries.
These queries are sent to the MongoDB server present in the Data
Layer. Now, the MongoDB server receives the queries and passes the
received queries to the storage engine. MongoDB server itself does not
directly read or write the data to the files or disk or memory. After
passing the received queries to the storage engine, the storage engine
is responsible to read or write the data in the files or memory basically
it manages the data.

MongoDB RDBMS
It is a non-relational and
It is a relational database.
document-oriented database.

It is suitable for hierarchical data It is not suitable for hierarchical


storage. data storage.

It has a dynamic schema. It has a predefined schema.

It centers around the CAP It centers around ACID


theorem (Consistency, properties (Atomicity,
Availability, and Partition Consistency, Isolation, and
tolerance). Durability).

In terms of performance, it is In terms of performance, it is


much faster than RDBMS. slower than MongoDB.

Advantages of MongoDB :

● It is a schema-less NoSQL database. You need not to design

the schema of the database when you are working with

MongoDB.

● It does not support join operation.

● It provides great flexibility to the fields in the documents.

● It contains heterogeneous data.

● It provides high performance, availability, scalability.


● It supports Geospatial efficiently.

● It is a document oriented database and the data is stored in

BSON documents.

● It also supports multiple document ACID transition.

● It does not require any SQL injection.

● It is easily integrated with Big Data Hadoop

Disadvantages of MongoDB :

● It uses high memory for data storage.

● You are not allowed to store more than 16MB data in the

documents.

● The nesting of data in BSON is also limited you are not

allowed to nest data more than 100 levels.

Where do we use MongoDB?


MongoDB is preferred over RDBMS in the following scenarios:
● Big Data: If you have huge amount of data to be stored in

tables, think of MongoDB before RDBMS databases.

MongoDB has built-in solution for partitioning and sharding

your database.

● Unstable Schema: Adding a new column in RDBMS is hard

whereas MongoDB is schema-less. Adding a new field does

not effect old documents and will be very easy.


● Distributed data Since multiple copies of data are stored

across different servers, recovery of data is instant and safe

even if there is a hardware failure.

A MongoDB Database can be called as the container for all the


collections.
● Collection is a bunch of MongoDB documents. It is similar

to tables in RDBMS.

● Document is made of fields. It is similar to a tuple in

RDBMS, but it has dynamic schema here. Documents of the

same collection need not have the same set of fields.

implementation json Bson data types:

JSON

JSON is Javascript Object Notation. It is a standard format used for storing


and interchanging the data. JSON is a user readable and it is a completely
language format. It is light weight. When read the JSON data of any
application so that is language independent. We can send information
through JSON very easily. JSON is basically a combination of key/value pair
and arrays. In JSON, we can embed more than one json documents in a
single json file. The maximum 100 documents can be embedded in a single
json document.

The data types supported by JSON are string, number, object, array, true,
false, and null.

For example
{

"_id" : 100,

"name" : "John",

"subject" : [

"Maths",

"English",

"Hindi"

],

"address" : {

"street" : "church road",

"city" : "faridabad",

"state" : "haryana"

}
BSON

BSON is a Binary Javascript Object notation. It is not in the human readable


format as it is in the binary format. In MongoDB, BSON is used to encrypt the
JSON data. It provides additional data types over the JSON data. It is also a
language independent, and can be easily parsed.

It supports the adding of documents and arrays within other documents and
arrays.

Lightweight: When used over the network, the JSON keeps the
overhead involved in processing extra header data to a minimum.

○ Traversable: It is designed to traverse easily across the network. This


helps in its role as the primary data representation for MongoDB.

○ Efficient: It allows C data types that allow easy and quick encoding
and decoding of data.

Differences between JSON and BSON.

JSON BSON

JSON is javascript object notation. BSON is Binary Javascript Object notation.

It is a standard file format type. It is a binary file format type.


JSON contains some basic data BSON contains some additional data types

types like string, numbers, Boolean, like date, timestamp, etc.

null.

Databases like AnyDB, redis, etc. The data in MongoDB is stored in a BSON

stores the data into the JSON format.

format.

JSON requires less space as BSON requires more space as compared to

compared to BSON. JSON.

It is comparatively less faster than It is faster as compared to BSON.

BSON.

It is used for the transmission of It is used for the storage of data.

data.

It does not have encoding and It has faster encoding and decoding

decoding technique. technique.

If we want to read any particular In BSON, indexes concept is used that

information from the JSON file then skips all the content which are not in use.

it needs to go through whole

content.
JSON format does not require to be It requires to be parsed as it can be easily

parsed as it is already human parsed by the machines.

readable.

JSON is a combination of objects The binary encoding technique provides

and arrays where an object is a some additional information such as

collection of key-value pairs while length of the string and object subtypes.

array is an ordered list of elements. BinData and Date are the additional data

types supported by BSON over the JSON

JSON vs BSON

JSON BSON

Encoding UTF-8 String Binary

Data Support String, String,


Boolean, Boolean,
Number, Array, Number
Object, null (Integer, Float,
Long,
Decimal128...),
Array, null,
Date, BinData

Readability Human and Machine Only


Machine

Real world application of NoSQL database

NoSQL databases can be used for a variety of applications, but


there are a few common use cases where NoSQL shines:

● E-commerce applications. ...


● Social media platforms. ...
● Internet of Things (IoT) ...
● Mobile applications. ...
● Gaming. ...
● Big data analytics.

Database security risk in mongodb

To protect your data, encrypt network traffic to and from the


database by configuring Transport Layer Security (TLS) and
Secure Sockets Layer (SSL).

concept of sharding to learn scalability in mongodb

What is sharding?
Sharding is a type of database partitioning that separates large
databases into smaller, faster, more easily managed parts. These
smaller parts are called data shards. The word shard means "a
small part of a whole."

Sharding is a method for distributing or partitioning data across multiple


machines. It is useful when no single machine can handle large
modern-day workloads, by allowing you to scale horizontally. Horizontal
scaling, also known as scale-out, refers to adding machines to share the

data set and load.Database sharding is a horizontal scaling strategy that

allocates additional nodes or computers to share the workload of an


application. Organizations benefit from horizontal scaling because of its
fault-tolerant architecture. When one computer fails, the others continue
to operate without disruption.

Scalability is the ability of a database to constantly adjust its


resources to meet application demands.

Sharding is a type of database partitioning that separates large


databases into smaller, faster, more easily managed parts. These
smaller parts are called data shards. The word shard means "a
small part of a whole."
Installing MongoDB:

http://www.mongodb.org/downloads and select your operating


system out of Windows, Linux, Mac OS X and Solaris

download : mongodb Community free server


open c drive - create folder name(Data)
Data new folder create DB

c-programs files-mongoDB-server-5.0-bin

mongod is server file (run this file)


open file mongo.exe
create database:
use product(db name)

show database
show dbs (all database show here)

create Collection
db.createCollection('proud')

db thn enter
current database show

use product
switched to db product
> db product
> db.createCollection('prod')
{ "ok" : 1 }

show dbs
admin 0.000GB
config 0.000GB
emp 0.000GB
employe 0.000GB
inventory 0.000GB
local 0.000GB
product 0.000GB
test 0.000GB

show collections
prod

db (current db m lane k liye )


product

for insert one data


db.users.insert({name:'varsha', age:'30'})
WriteResult({ "nInserted" : 1 })

note : users is collection

show collections
prod
users

db.users.drop()(delete user collection)


true (true mean delete table)

show collections
prod
(only one collection here)

db.prod.drop() (another collection delete)


true
> show collections
(check collection is blank)

db.dropDatabase()
(for delete database drop)

CURD Operations (create , update , read, delete)

create new library project

use lib (create databse)


db (in current db)
lib

db.createCollection('books')
(create a new collection)

show collections

Read operation
insert 3 types
insert()
insertOne()
insertMany()

insert ():

db.books.insert({name:'java' , price:'100' , pages:'500'})


one row inserted

db.books.find()
to check insert data in collections

insertOne()
db.books.insertOne({name:'PHP' , price:'1000' , pages:'580'})
{
"acknowledged" : true,
"insertedId" : ObjectId("64fffff1755d25d0ba46fac4")
}

insertMany()
db.books.insertMany([{}.{},{},{}])
multiple array separate by ,

for ex

db.books.insertMany([{name:'PHP',price:'1000',pages:'580'},{name:'j
avascript',pages:'200'}])
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("65000148755d25d0ba46fac5"),
ObjectId("65000148755d25d0ba46fac6")
]

db.books.find()
all inserted data are here

{ "_id" : ObjectId("64ffff11755d25d0ba46fac3"), "name" : "java",


"price" : "100", "pages" : "500" }
{ "_id" : ObjectId("64fffff1755d25d0ba46fac4"), "name" : "PHP",
"price" : "1000", "pages" : "580" }
{ "_id" : ObjectId("65000148755d25d0ba46fac5"), "name" : "PHP",
"price" : "1000", "pages" : "580" }
{ "_id" : ObjectId("65000148755d25d0ba46fac6"), "name" :
"javascript", "pages" : "200" }

db.books.insertOne({name:'PHP' , price:'1000' , pages:'580' ,


author:'harry'})
{
"acknowledged" : true,
"insertedId" : ObjectId("65000204755d25d0ba46fac7")
}
> db.books.find()
{ "_id" : ObjectId("64ffff11755d25d0ba46fac3"), "name" : "java",
"price" : "100", "pages" : "500" }
{ "_id" : ObjectId("64fffff1755d25d0ba46fac4"), "name" : "PHP",
"price" : "1000", "pages" : "580" }
{ "_id" : ObjectId("65000148755d25d0ba46fac5"), "name" : "PHP",
"price" : "1000", "pages" : "580" }
{ "_id" : ObjectId("65000148755d25d0ba46fac6"), "name" :
"javascript", "pages" : "200" }
{ "_id" : ObjectId("65000204755d25d0ba46fac7"), "name" : "PHP",
"price" : "1000", "pages" : "580", "author" : "harry" }

Update operation
update 3 types
update ()
update One()
updateMany()

update ()
db.books.update({_id:
ObjectId("64ffff11755d25d0ba46fac3")},{name:'reference
java',pages:'6000', price:'900'})

db.books.find()
{ "_id" : ObjectId("64ffff11755d25d0ba46fac3"), "name" : "reference
java", "pages" : "6000", "price" : "900" }
{ "_id" : ObjectId("64fffff1755d25d0ba46fac4"), "name" : "PHP",
"price" : "1000", "pages" : "580" }
{ "_id" : ObjectId("65000148755d25d0ba46fac5"), "name" : "PHP",
"price" : "1000", "pages" : "580" }
{ "_id" : ObjectId("65000148755d25d0ba46fac6"), "name" :
"javascript", "pages" : "200" }
{ "_id" : ObjectId("65000204755d25d0ba46fac7"), "name" : "PHP",
"price" : "1000", "pages" : "580", "author" : "harry" }

updateOne()

db.books.updateOne({_id:
ObjectId("64ffff11755d25d0ba46fac3")},{$set:{name:'playing
book',price:'200',pages:'700'}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

db.books.find()

{ "_id" : ObjectId("64ffff11755d25d0ba46fac3"), "name" : "playing


book", "pages" : "700", "price" : "200" }
{ "_id" : ObjectId("64fffff1755d25d0ba46fac4"), "name" : "PHP",
"price" : "1000", "pages" : "580" }
{ "_id" : ObjectId("65000148755d25d0ba46fac5"), "name" : "PHP",
"price" : "1000", "pages" : "580" }
{ "_id" : ObjectId("65000148755d25d0ba46fac6"), "name" :
"javascript", "pages" : "200" }
{ "_id" : ObjectId("65000204755d25d0ba46fac7"), "name" : "PHP",
"price" : "1000", "pages" : "580", "author" : "harry" }
rename operations

db.books.updateOne({_id:
ObjectId("64fffff1755d25d0ba46fac4")},{$rename:{name:'bookname'
}})

db.books.find()
{ "_id" : ObjectId("64ffff11755d25d0ba46fac3"), "name" : "playing
book", "pages" : "700", "price" : "200" }
{ "_id" : ObjectId("64fffff1755d25d0ba46fac4"), "price" : "1000",
"pages" : "580", "bookname" : "PHP" }
{ "_id" : ObjectId("65000148755d25d0ba46fac5"), "name" : "PHP",
"price" : "1000", "pages" : "580" }
{ "_id" : ObjectId("65000148755d25d0ba46fac6"), "name" :
"javascript", "pages" : "200" }
{ "_id" : ObjectId("65000204755d25d0ba46fac7"), "name" : "PHP",
"price" : "1000", "pages" : "580", "author" : "harry" }

remove()
deleteOne()
deleteMany()

remove()
db.books.remove({_id: ObjectId("64ffff11755d25d0ba46fac3")})

db.books.find()

db.books.find().pretty()

{
"_id" : ObjectId("64fffff1755d25d0ba46fac4"),
"price" : "1000",
"pages" : "580",
"bookname" : "PHP"
}
{
"_id" : ObjectId("65000148755d25d0ba46fac5"),
"name" : "PHP",
"price" : "1000",
"pages" : "580"
}
{
"_id" : ObjectId("65000148755d25d0ba46fac6"),
"pages" : "200",
"playing book" : "javascript"
}
{
"_id" : ObjectId("65000204755d25d0ba46fac7"),
"name" : "PHP",
"price" : "1000",
"pages" : "580",
"author" : "harry"
}

limit()

db.books.find().limit(2)
{ "_id" : ObjectId("64fffff1755d25d0ba46fac4"), "price" : "1000",
"pages" : "580", "bookname" : "PHP" }
{ "_id" : ObjectId("65000148755d25d0ba46fac5"), "name" : "PHP",
"price" : "1000", "pages" : "580" }

limit().pretty()

db.books.find().limit(2).pretty()
{
"_id" : ObjectId("64fffff1755d25d0ba46fac4"),
"price" : "1000",
"pages" : "580",
"bookname" : "PHP"
}
{
"_id" : ObjectId("65000148755d25d0ba46fac5"),
"name" : "PHP",
"price" : "1000",
"pages" : "580"
}
sort()

db.books.find().sort({price:1})
{ "_id" : ObjectId("65000148755d25d0ba46fac6"), "pages" : "200",
"playing book" : "javascript" }
{ "_id" : ObjectId("64fffff1755d25d0ba46fac4"), "price" : "1000",
"pages" : "580", "bookname" : "PHP" }
{ "_id" : ObjectId("65000148755d25d0ba46fac5"), "name" : "PHP",
"price" : "1000", "pages" : "580" }
{ "_id" : ObjectId("65000204755d25d0ba46fac7"), "name" : "PHP",
"price" : "1000", "pages" : "580", "author" : "harry" }

db.books.find().sort({price:1}).pretty()
db.books.find().sort({price:-1})(desencding order)

You might also like