Download as pdf or txt
Download as pdf or txt
You are on page 1of 50

UNIT-IV

MongoDB

Dr. C. Raghavendra
Associate Professor,
Department of Emerging Technologies,
CVR College of Engineering, HYD. 1
Contents

• Introduction to MongoDB, key features of MongoDB, MongoDB shell,

MongoDB Data bases, MongoDB collections, MongoDB CRUD

Operations, Real Time Data base Fire base CRUD operations.

2
Introduction to MongoDB
• MongoDB, the most popular NoSQL (Not only SQL)
database, is an open-source document-oriented database
that provides high performance, high availability, and
automatic scaling.

• It is an open source product, developed and supported by a


company named 10gen.

• The term NoSQL means ‘non-relational’. It is used as an


alternative to traditional relational databases. 3
Cont.
• It means that MongoDB isn’t based on the table-like relational
database structure but provides an altogether different
mechanism for storage and retrieval of data.

• This format of storage is called BSON ( similar to JSON format).

• NoSQL databases are quite useful for working with large sets of
distributed data.

• MongoDB is a tool that can manage document-oriented


information, store or retrieve information.
4
Purpose of Building MongoDB
• All the modern applications require big data, fast features
development, flexible deployment, and the older database
systems not competent enough, so the MongoDB was
needed.

5
Features of MongoDB
1. Support ad hoc queries

• In MongoDB, you can search by field, range query and it


also supports regular expression searches.

2. Indexing

• Indexes can be created to improve the performance of


searches within MongoDB. Any field in a MongoDB
document can be indexed.
6
Cont.
3. Replication

• MongoDB supports Master Slave replication.

• A master can perform Reads and Writes and a Slave copies data from
the master and can only be used for reads or back up (not writes)

4. Duplication of data

• MongoDB can run over multiple servers. The data is duplicated to


keep the system up and also keep its running condition in case of
hardware failure.
7
Cont.
5. Load balancing

• It has an automatic load balancing configuration because of data


placed in shards.

6. Supports map reduce and aggregation tools.

7. Uses JavaScript instead of Procedures.

8. It is a schema-less database written in C++.

9. Provides high performance.

10. Stores files of any size easily without complicating your stack.
8
Cont.
11. Easy to administer in the case of failures.

12. It also supports:

• JSON data model with dynamic schemas

• Auto-sharding for horizontal scalability

• Built in replication for high availability

• Now a day many companies using MongoDB to create new


types of applications, improve performance and availability.
9
SQL NoSQL
Relational Database Management Non-relational or distributed
System(RDBMS) database system.
These databases have fixed or static or They have dynamic schema
predefined schema
These databases are not suited for These databases are best suited for
hierarchical data storage. hierarchical data storage.
These databases are best suited for These databases are not so good for
complex queries complex queries
Vertically Scalable Horizontally scalable
Follows ACID property Follows CAP(consistency, availability,
partition tolerance)
MongoDB shell
• MongoDB have a JavaScript shell that allows interaction
with MongoDB instance from the command line.

• If you want to create a table, you should name the table


and define its column and each column's data type.

• The shell is useful for performing administrative functions


and running instances.

11
How to run the shell
• To start the shell, open command prompt, run it as a
administrator then run the mongo executable:

$ mongo

• You should start mongoDB before starting the shell because


shell automatically attempt to connect to a MongoDB server
on startup.

• The shell is a full-featured JavaScript interpreter.


12
Cont.
• Let us take a simple mathematical program:

>x= 100

100

>x/ 5;

20

13
Cont.
• You can also use the JavaScript libraries

> "Hello, World!".replace("World", "MongoDB");

Hello, MongoDB!

• When you press "Enter", the shell detect whether the JavaScript
statement is complete or not.

• If the statement is not completed, the shell allows you to continue


writing it on the next line.

• If you press "Enter" three times in a row, it will cancel the half-
formed command and get you back to the > prompt.
14
Databases and Collections
• MongoDB stores data records as documents (specifically
BSON documents) which are gathered together in
collections.

•A database stores one or more collections of documents.

• In MongoDB, databases hold one or more collections of


documents.

15
Cont.
• To select a database to use, in mongosh, issue the use <db> statement, as
in the following example:

use myDB

Create a Database

• If a database does not exist, MongoDB creates the database when you first
store data for that database. As such, you can switch to a non-existent
database and perform the following operation in mongosh:

use myNewDB

db.myNewCollection1.insertOne( { x: 1 } )
16
Cont.
• The insertOne() operation creates both the database
myNewDB and the collection myNewCollection1 if they do
not already exist.

• Be sure that both the database and collection names follow


MongoDB Naming Restrictions.

17
Cont.
Collections

• MongoDB stores documents


in collections.

• Collections are analogous to


tables in relational
databases.

18
Database, Collection, Document

19
Cont.
Database:

• In simple words, it can be called the physical container for


data.

• Each of the databases has its own set of files on the file
system with multiple databases existing on a single
MongoDB server.

20
Cont.
Collection:

•A group of database documents can be called a collection.

• The RDBMS equivalent to a collection is a table.

• There are no schemas when it comes to collections.

• Inside the collection, various documents can have varied


fields, but mostly the documents within a collection are
meant for the same purpose or for serving the same end
goal. 21
Ex:

22
Ex:

23
Comparing MongoDB vs SQL

24
Cont.
Document:

•A set of key-value pairs can be designated as a document.

• Documents are associated with dynamic schemas.

• The benefit of having dynamic schemas is that a document


in a single collection does not have to possess the same
structure or fields.

25
Cont.

26
Cont.

27
Note
Primary key

A required value that uniquely identifies a document within a


collection. The primary key is always implemented as the
field.

28
Sharding
• Sharding is a method for distributing a single dataset across
multiple databases, which can then be stored on multiple
machines.

• This allows for larger datasets to be split in smaller chunks and


stored in multiple data nodes, increasing the total storage
capacity of the system.

• The word “Shard” means “a small part of a whole“. Hence


Sharding means dividing a larger part into smaller parts.
29
What is Sharding in MongoDB?
• Sharding is a form of scaling known as horizontal scaling or
scale-out, as additional nodes are brought on to share the
load. Horizontal scaling allows for near-limitless scalability
to handle big data and intense workloads.

• In contrast, vertical scaling refers to increasing the power


of a single machine or single server through a more
powerful CPU, increased RAM, or increased storage
capacity.
30
Cont.
• Sharding is a concept in MongoDB, which splits large data
sets into small data sets across multiple MongoDB
instances.

• Sometimes the data within MongoDB will be so huge, that


queries against such big data sets can cause a lot of CPU
utilization on the server. To tackle this situation, MongoDB
has a concept of Sharding, which is basically the splitting of
data sets across multiple MongoDB instances.
31
Cont.
• The collection which could be large in size is actually split
across multiple collections or Shards as they are called.
Logically all the shards work as one collection.

32
Replication and Sharding
• Replication: The primary server node copies data onto
secondary server nodes. This can help increase data
availability and act as a backup, in case if the primary
server fails.

• Sharding: Handles horizontal scaling across servers using


a shard key.

33
• Advantages of sharding:

• Increased read/write throughput

• Increased storage capacity

• High availability

• Disadvantages of sharding:

• Query overhead

• Complexity of administration

• Increased infrastructure costs


34
CRUD OPERATIONS
1. Create Operation

2. Read Operation

3. Update Operation

4. Delete Operation

35
1. Create Operations

• Create or insert operations add new documents to a collection.

• If the collection does not currently exist, insert operations will


create the collection.

• MongoDB provides the following methods to insert documents


into a collection:

I. db.collection.insertOne()

II. db.collection.insertMany()
36
Cont.
• In MongoDB, insert operations target a single collection. All
write operations in MongoDB are atomic on the level of a
single document.

37
Ex:
Insert a Single Document

• db.collection.insertOne() inserts a single document into a collection.

• The following example inserts a new document into the inventory


collection

db.inventory.insertOne(

{ item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5,


uom: "cm" } }

)
38
Cont.
• To retrieve the document that you just inserted, query the collection:

db.inventory.find( { item: "canvas" } )

Insert Multiple Documents

db.inventory.insertMany([

{ item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" }},

{ item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } },

{ item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom:
"cm" } }

])
39
Read Operations
• Read operations retrieve documents from a collection.

• MongoDB provides the following methods to read


documents from a collection:

db.collection.find()

• You can specify query filters or criteria that identify the


documents to return.

40
Cont.

41
Update Operations
• Update operations modify existing documents in a
collection. MongoDB provides the following methods to
update documents of a collection:

1. db.collection.updateOne()

2. db.collection.updateMany()

3. db.collection.replaceOne()

42
Cont.
• In MongoDB, update operations target a single collection.

• You can specify criteria, or filters, that identify the


documents to update. These filters use the same syntax as
read operations.

43
Delete Operations
• Delete operations remove documents from a collection.

• MongoDB provides the following methods to delete


documents of a collection:

• db.collection.deleteOne()

• db.collection.deleteMany()

44
Cont.
• In MongoDB, delete operations target a single collection.

• You can specify criteria, or filters, that identify the


documents to remove.

• These filters use the same syntax as read operations.

45
Real Time Database Firebase CRUD operations

• Firebase is a back-end service that your app can interact


with. It has a lot of features such as Cloud Firestore, Real-
Time Database, User Authentication, File Storage, and
much more.

• With Firebase, we do not have to create database schema


upfront because Firebase is very flexible and allows
changes to the schema as we progress with our application.

46
Cont.
• As our application evolves over time, it’s recommended to
build an app with Firebase and change the schema
simultaneously based on the requirements.

• Firebase lets you query data from the real-time database


which is completely different than traditional SQL queries.

47
Cont.
• What Are We Building?

• Get Users List: This simple JavaScript app fetches users


data from Firebase Real-Time Database using Firebase SDK
and populates data on the browser.

• Get Selected User: When selecting a user on the left,


more information about the user appears on the right.

48
• We just need the 6 steps below in order to achieve the final outcome:

• STEP #1: Setting up a firebase app on the firebase console

• STEP #2: Setting up our simple user list javascript project

• STEP #3: Initialize firebase into the app by adding the code snippet

• STEP #4: Enable read and write permission to the firebase database

• STEP #5: Import users schema JSON file into the database

• STEP #6: Read user’s data from the firebase using child_added()
method
49
Thank You
50

You might also like