0% found this document useful (0 votes)
4 views

MongoDB Lecture 1

The document provides an overview of MongoDB, a cross-platform, document-oriented database known for its high performance, scalability, and flexible schema design. It discusses key features such as sharding, replication, and various data types supported by MongoDB, along with comparisons to traditional relational databases like MySQL. Additionally, it outlines the installation process and basic commands for managing databases and collections within MongoDB.

Uploaded by

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

MongoDB Lecture 1

The document provides an overview of MongoDB, a cross-platform, document-oriented database known for its high performance, scalability, and flexible schema design. It discusses key features such as sharding, replication, and various data types supported by MongoDB, along with comparisons to traditional relational databases like MySQL. Additionally, it outlines the installation process and basic commands for managing databases and collections within MongoDB.

Uploaded by

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

MONGODB AND BUILDING REST API USING

MONGODB

by
Manya Gidwani
Assistant Professor
IT DepartmentSAKEC
CONTENTS
Introduction to MongoDB
Document Database
DataTypes in MongoDB
? MongoDB is a cross-platform, document
oriented database that provides, high
performance, high availability, and easy
scalability. MongoDB works on concept
of collection and document.
? Database is a physical container for
collections. Each database gets its own
set of files on the file system. A single
MongoDB server typically has multiple
databases.
? Collection is a group of MongoDB documents.
? It is the equivalent of an RDBMS table.
? Collections do not enforce a schema.
? Documents within a collection can have
different fields. Typically, all documents in a
collection are of similar or related purpose.
? A document is a set of key-value pairs.
? Documents have dynamic schema.
? Dynamic schema means that documents in
the same collection do not need to have the
same set of fields or structure, and common
fields in a collection's documents may hold
different types of data.
RDBMS MongoDB

Database Database

Table Collection

Tuple/Row Document

column Field

Primary Key Primary Key (Default key _id


provided by mongodb itself)
WHY 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.
? Flexibility: MongoDB uses documents that can contain sub
documents in complex hierarchies making it expressive and
flexible. MongoDB can map objects from any programming
language, ensuring easy implementation and maintenance.
? Flexible Query Model:The user can selectively index some
parts of each document or a query based on regular
expressions, ranges, or attribute values, and have as many
properties per object as needed by the application layer.
? Native Aggregation: Native aggregation allows users to
extract and transform data from the database. The data can
either be loaded into a new format or exported to other data
sources.
? Schema-less model: Applications get the power and
responsibility to interpret different properties found in a
collection's documents.
WHY MONGODB?
? Indexing: Index can be used to improve performance
of searching in MONGODB. You can index any field in a
document.
? 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).
? Load Balancing and scaling: It is built to scale, both
vertically and horizontally. Using the technique of
sharding, an architect can achieve both write and read
scalability. Data balancing occurs automatically and
transparently to the user by the shard balancer.
FEATURES OF MONGODB
FEATURES OF MONGODB
1. General-Purpose Database: MongoDB can serve diverse sets of data and
multiple purposes within a single application.
2. Flexible Schema Design: The document-oriented approach allows non-
defined attributes to be modified on the fly. This is a key contrast between
MongoDB and other relational databases.
3. Load Balancing and Scalability: It is built to scale, both vertically and
horizontally. Using the technique of sharding, an architect can achieve both
write and read scalability. Data balancing occurs automatically and
transparently to the user by the shard balancer.
4. Aggregation Framework: MongoDB offers an Extract, Transform, Load
(ETL) framework which eliminates the need for complex data pipelines.
5. Native Replication :Data gets replicated across a replica set without a
complicated setup.
6. Security Features: Authentication and authorization are taken into
account.
7. JSON: JSON is widely used across for frontend and API communication. It
only makes sense for the database to use the same protocol.
8. MapReduce: MongoDB offers a great tool, MapReduce to build data
pipelines.
ADVANTAGES OF MONGODB
MongoDB brings a host of benefits to the table. Its advantages include:
? NoSQL databases are cheaper and easier to maintain. NoSQL databases
have features like easier data distribution, simpler data models, and
automatic repair. These benefits require less administrative costs and,
consequently, are less expensive.
? It’s open-source and incurs fewer server costs. Open-source is free.
NoSQL databases use cheaper servers, so the price of data storage and
processing per gig is significantly lower.
? It’s easily and highly scalable. Since NoSQL databases like MongoDB
expand horizontally, you can scale by adding more machines to your
resource pool.
? It supports integrated caching. System memory caching boosts data
output performance.
? MongoDB has no schema hassles. You can place data into a NoSQL
database without requiring a predefined schema, so you can change
the data model and formats without disrupting applications.
? It’s user-friendly. MongoDB offers plenty of useful features (Ad-hoc
queries, aggregation, capped collection, file storage, indexing, load
balancing, replication, server-side JavaScript execution) that makes it a
user-friendly database.
SHARDING IN MONGODB
? Sharding : It allows horizontal scaling.
? In the above diagram, there are three main components −
? Shards − Shards are used to store data. They provide high
availability and data consistency. In production environment,
each shard is a separate replica set.
? Config Servers − Config servers store the cluster's
metadata. This data contains a mapping of the cluster's data
set to the shards. The query router uses this metadata to
target operations to specific shards. In production
environment, sharded clusters have exactly 3 config servers.
? Query Routers − Query routers are basically mongo
instances, interface with client applications and direct
operations to the appropriate shard. The query router
processes and targets the operations to shards and then
returns results to the clients. A sharded cluster can contain
more than one query router to divide the client request load.
A client sends requests to one query router. Generally, a
sharded cluster have many query routers.
WORKING OF MONGODB
The entire database
consists of collections.
These collections hold
multiple documents, and
since MongoDB is
schemaless, the
documents in one
collection need not be
similar.
All data is stored key-
value pairs. At the
backend, MongoDB
converts JSON data into
a binary format known
as BSON (Binary
JavaScript Object
Notation.).
APPLICATION OF MONGODB
MONGODB VS MYSQL
MongoDB MySQL

Priority Cloud-friendly High data security

Unstructured, or structured
Data Structure data that will potentially Structured
grow fast

Data Representation JSON documents Tables and rows

JOIN Support No Yes

Structured Query Language


Query Language JavaScript
(SQL)

Must define columns and


Schema No need to define
tables

Developer Productivity Fast Slow

Atomic Transactions
Doesn’t fully support all
(e.g., having several Supports atomic
operations but supports
operations within a transactions
multi-document transactions
transaction)
DOCUMENT DATABASE
? A document database (also known as a document-oriented
database or a document store) is a database that stores
information in documents.
? A document is a record in a document database. A document
typically stores information about one object and any of its
related metadata.
? Documents store data in field-value pairs. The values can be a
variety of types and structures, including strings, numbers,
dates, arrays, or objects. Documents can be stored in formats
like JSON, BSON, and XML.
DOCUMENT DATABASE
? A collection is a group of documents.
Collections typically store documents that
have similar contents.
? Not all documents in a collection are required
to have the same fields, because document
databases have a flexible schema. Note that
some document databases provide schema
validation, so the schema can optionally be
locked down when needed.
DATATYPES IN MONGODB
? MongoDB supports many data types whose list is given below:
? String : This is the most commonly used datatype to store the data.
String in MongoDB must be UTF-8 valid.
db.TestCollection.insert({"string data type" : "This is a sample
message."})
? Integer :This type is used to store a numerical value. Integer can be 32
bit or 64 bit depending upon your server.
db.TestCollection.insert({"Integer example": 62})
? Boolean : This type is used to store a boolean (true/ false) value.
db.TestCollection.insert({"Nationality Indian": true})
? Double : This type is used to store floating point values.
? db.TestCollection.insert({"double data type": 3.1415})
? Arrays :This type is used to store arrays or list or multiple values into
one key.
var degrees = ["BCA", "BS", "MCA"]
db.TestCollection.insert({" Array Example" : " Here is an example of
array", " Qualification" : degrees})
DATATYPES IN MONGODB

? Min/ Max keys : This type is used to compare a value against the
lowest and highest BSON elements.
? Date : This datatype is used to store the current date or time in UNIX
time format. You can specify your own date time by creating object of
Date and passing day, month, year into it.
var date=new Date()
var date2=ISODate()
var month=date2.getMonth()
db.TestCollection.insert ({"Date":date, "Date2":date2,
"Month":month})
? Timestamp : ctimestamp. This can be handy for recording when a
document has been modified or added.
? Object : This datatype is used for embedded documents.

var embeddedObject ={"English" : 94, "ComputerSc." : 96,


"Maths" : 80, "GeneralSc." : 85}
db.TestCollection.insert({"Object data type" : "This is Object",
"Marks" : embeddedObject})
DATATYPES IN MONGODB
? Null : This type is used to store a Null value.
db.TestCollection.insert({" EmailID ":
null})
? Symbol : This datatype is used identically to
a string; however, it's generally reserved for
languages that use a specific symbol type.
? Binary data : This datatype is used to store
binary data.
INSTALLATION OF MONGODB
? Step 1: To install MongoDB on Windows, first
download the latest release of MongoDB from
https://www.mongodb.com/try/download/com
munity
INSTALLATION OF MONGODB
? Step 2 : Run MSI and Click Next.
INSTALLATION OF MONGODB
? Step 3: Now, choose Complete to install
MongoDB completely.
? Then, select the radio button "Run services
as Network service user.“
? To run server type this in cmd
C:\Program Files\MongoDB\Server\5.0\
bin>mongod

? To run client type this in cmd


C:\Program Files\MongoDB\Server\5.0\
bin>mongo.exe
? The use Command in MongoDB is used to
create
>use mydb database.
switched to db mydb
?
Touse DATABASE_NAME
check your currently selected database use the
command db
>db mydb

If you want to check your databases list, then use the


command show dbs.

>show dbs local 0.78125GB test 0.23012GB


Delete Database
db.dropDatabase()

Create Collection
db.createCollection(name, options)

>db.createCollection("mycollection")
{ "ok" : 1 }
>show collections mycollection system.indexes
Insert Records
? >db.movie.insert({"name":"tutorials point"})
? >show dbs
local 0.78125GB
mydb 0.23012GB
test 0.23012GB
_id is 12 bytes hexadecimal number unique for
every document in a collection.
? To insert multiple documents in single query,
you can pass an array of documents in insert()
command.
? The save() method replaces the existing document
with the new document passed in save() method
? Syntax

>db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DA
TA})
? The remove() Method is used to remove
document from the collection. remove() method
accepts two parameters. One is deletion criteria and
second
Thank
You

You might also like