Unit-4 MongoDB Students

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

Contents

• SQL vs NoSQL
• NoSQL Features & Types
• What is MongoDB?
• MongoDB Features
• MongoDB Data Types
• Installation MongoDB on Windows
Ajay Parashar
• MongoDB CRUD Operations
IT@ HCST
• Node.js with MongoDB

Ajay Parashar IT@HCST

• NoSQL (often interpreted as Not only SQL) database


• It provides a mechanism for storage and retrieval of data that is modeled
in means other than the tabular relations used in relational databases.

SQL vs NoSQL SQL

Relational Database Management System (RDBMS)


NoSQL

Non-relational or distributed database system.

These databases have fixed or static or predefined schema They have dynamic schema

These databases are best suited for complex queries These databases are not so good for complex queries

Vertically Scalable Horizontally scalable

Follows ACID property Follows BASE property


Ajay Parashar IT@HCST Ajay Parashar IT@HCST
• ACID Properties:

1. Atomicity; The entire transaction • CAP Properties:


takes place at once or doesn't
happen at all. 1. Consistency; that the nodes will have the
Relational Databases same copies of a replicated data item NoSQL Databases
visible for various transactions
2. Consistency; The database is
consistent before and after the
Atomicity Consistency transaction. 2. Availability; that each read or write Consistency
request for a data item will either be
processed successfully or will receive a
message that the operation cannot be
ACID 3. Isolation; Multiple transactions completed Availability CAP
occur independently without
interference.
3. Partition tolerance; the system can Partition tolerance
Isolation Durability continue operating even if the network
4. Durability; The changes of connecting the nodes has a fault that
results in two or more partitions, where
successful transaction occurs even if the nodes in each partition can only
the systems failure occurs communicate among each other.
Ajay Parashar IT@HCST Ajay Parashar IT@HCST

FEATURES

NoSQL Features & Types Fexible Schemas


Fast queries due
to the data model

Ease of use for


Horizotal scaling
developers

Ajay Parashar IT@HCST Ajay Parashar IT@HCST


FEATURES TYPES • NoSQL database are primarily called as non-SQL or non-
relational database. MongoDB is Scalable (able to be changed in size or
scale), open-source, high-perform, document-oriented database.
Fast queries due Document Key-value
Fexible Schemas
to the data model databases databases
• Remember:
• Horizontal scaling means that you scale by adding more machines
Ease of use for Wide-column into your pool of resources.
Horizotal scaling Graph databases
developers stores
• Vertical scaling means that you scale by adding more power (CPU,
RAM) to an existing machine.

Ajay Parashar IT@HCST Ajay Parashar IT@HCST

Key-value stores, or key-value databases, implement a simple data model that pairs
a unique key with an associated value.
Key-value stores e.g.
• Redis, Cassandra

Wide-column stores organize data tables as columns instead of as rows.


Column-oriented e.g.
• hBase

Document databases, also called document stores, store semi-structured data and
descriptions of that data in document format.
Document oriented e.g.
• MongoDB, CouchDB

Graph data stores organize data as nodes.


Graph e.g.
• Neo4j

Ajay Parashar IT@HCST Ajay Parashar IT@HCST


A database management
system designed to
A general-purpose rapidly develop web
document database applications and internet
designed for modern infrastructure.
application development

What is MongoDB?
and for the cloud.

A good NoSQL document


database with a range of
features that, in the
open-source NoSQL
world, are hard to beat.

Ajay Parashar IT@HCST Ajay Parashar IT@HCST

A database management
system designed to
rapidly develop web MongoDB stores data
A general-purpose as JSON/BSON (Binary
applications and internet Document-Oriented, Database Collections
document database JSON) documents
infrastructure. No Sequel (NoSQL)
designed for modern
application development
and for the cloud.

A good NoSQL document In MongoDB, a


database with a range of collection is a group of
features that, in the documents
open-source NoSQL
world, are hard to beat.

Ajay Parashar IT@HCST Ajay Parashar IT@HCST


High
Performance

Auto
MongoDB Features
Indexing
Replication

High Horizontal
Availability Scalability

Load
Balancing
Ajay Parashar IT@HCST Ajay Parashar IT@HCST

• String
This is the most commonly used datatype to store the data. String in MongoDB must be
UTF-8 valid.
• Integer
This type is used to store a numerical value. Integer can be 32 bit or 64 bit depending
upon your server.
MongoDB Data Types • Double
This type is used to store floating point values.
• 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.
• Boolean
This type is used to store a boolean (true/ false) value.
Ajay Parashar IT@HCST Ajay Parashar IT@HCST
• Object ID
This datatype is used to store the document’s ID.
• Array
This type is used to store arrays or list or multiple values into one key.
• Timestamp
This can be handy for recording when a document has been modified or added. Installation MongoDB on Windows
• Code
This datatype is used to store JavaScript code into the document.
• Regular Expression
This datatype is used to store regular expression.

Ajay Parashar IT@HCST Ajay Parashar IT@HCST

• Go to MongoDB download Page and • Click Run when the MongoDB


click download as shown in the installation windows pops up.
screenshot.

• A .msi file like this mongodb-win32-


x86_64-2008plus-ssl-3.4.7-signed will
be downloaded in your system. Double
click on the file to run the installer.

Ajay Parashar IT@HCST Ajay Parashar IT@HCST


• Click Next when the MongoDB • Accept the MongoDB user Agreement
installation windows pops up. and click Next.

Ajay Parashar IT@HCST Ajay Parashar IT@HCST

• When the setup asks you to choose the • Click Next when the MongoDB service
Setup type, choose Complete. configuration. MongoDB will be
installed in the windows service

Ajay Parashar IT@HCST Ajay Parashar IT@HCST


• Choose Install MongoDB Compass if • Step 8: Click Install to begin the
you want to use the MongoDB User installation.
Interface, or ignore it and continue by
clicking Next in the Install MongoDB
Compass window

Ajay Parashar IT@HCST Ajay Parashar IT@HCST

Print a list of all databases on the server.


• The ObjectId class is the default primary key for a MongoDB document and is show { dbs | databases }
usually found in the _id field in an inserted document.
• show dbs
• show databases # Returns: all database name.
• The _id field must have a unique value. You can think of the _id field as the
document’s primary key.
db.getName()
• MongoDB uses ObjectIds as the default value of _id field of each document, • db
which is auto generated while the creation of any document. • db.getName() # Returns: the current database
name.

Ajay Parashar IT@HCST Ajay Parashar IT@HCST


Switch current database to <db>. The mongo shell variable db is set to the current Removes the current database, deleting the associated data files.
database.

use <db> db.dropDatabase()

• use db1 • use db1


• db.dropDatabase()

Ajay Parashar IT@HCST Ajay Parashar IT@HCST

RDBMS MongoDB

Database Database

Table Collection

MongoDB CRUD Operations Tuple/Row Document

column Field

Table Join Embedded Documents

Primary Key
Primary Key
(Default key _id provided by MongoDB itself)

Ajay Parashar IT@HCST Ajay Parashar IT@HCST


• ObjectId in the MongoDB is same as the primary key in the conventional RDBMS.
CREATE DATABASE
• It is by default set by MongoDB for every document that is created inside any
MongoDB use DATABASE_NAME is used to create database. The command will create a
collection. new database if it doesn't exist, otherwise it will return the existing database.

• ObjectIds are small, unique, fast to generate and ordered.

• ObjectId values comprises of a 12 bytes hexadecimal number which is unique for


every document.
• _id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id, 3 bytes
counter)
• "_id": ObjectId("5901832c91427cac52e9ea8f")

Ajay Parashar IT@HCST Ajay Parashar IT@HCST

• SQL Server
CREATE DATABASE databasename; INSERT DOCUMENT
Example: CREATE DATABASE testdb;

• MySQL Single Insert Multiple Insert


CREATE DATABASE databasename;
Example: CREATE DATABASE testdb;

Ajay Parashar IT@HCST Ajay Parashar IT@HCST


• SQL Server
✓ Single
INSERT INTO tablename (c1,c2,...)
VALUES (v11,v12,...);
✓ Multiple INSERT DOCUMENT - SINGLE
INSERT INTO tablename (c1,c2,...)
VALUES (v11,v12,...), (v21,v22,...), ….. , (vnn,vn2,...);

• MySQL
✓ Single
INSERT INTO tablename (c1,c2,...)
VALUES (v11,v12,...);
✓ Multiple
INSERT INTO tablename (c1,c2,...)
VALUES (v11,v12,...), (v21,v22,...), ….. , (vnn,vn2,...);

Ajay Parashar IT@HCST Ajay Parashar IT@HCST

$eq Matches values that are equal to a specified value.

$gt Matches values that are greater than a specified value.


INSERT DOCUMENT - MULTIPLE
$gte Matches values that are greater than or equal to a specified value.

$lt Matches values that are less than a specified value.

$lte Matches values that are less than or equal to a specified value.

$ne Matches all values that are not equal to a specified value.

$in Matches any of the values specified in an array.

$nin Matches none of the values specified in an array.

Ajay Parashar IT@HCST Ajay Parashar IT@HCST


$eq $ne
{ field: { $eq: value } } { field: { $ne: value } }
QUERY DOCUMENTS
SELECT * FROM tablename;

$gt $gte
Select All Documents
{ field: { $gt: value } } { field: { $gte: value } }
SELECT * FROM tablename WHERE column;

$lt $lte Specify Equality


{ field: { $lt: value } } { field: { $lte: value } }
SELECT * FROM tablename WHERE columnname IN ;

$in Specify Conditions Using Query Operators


{ field: { $in: [ <value1>, <value2>, ..., <valueN> ] } }

$nin
{ field: { $nin: [ <value1>, <value2>, ..., <valueN> ] } }
Ajay Parashar IT@HCST Ajay Parashar IT@HCST

SELECT ALL DOCUMENTS


SPECIFY EQUALITY

Ajay Parashar IT@HCST Ajay Parashar IT@HCST


SPECIFY CONDITIONS USING
QUERY OPERATORS
Joins query clauses with a logical OR returns all documents that
$or
match the conditions of either clause.

Joins query clauses with a logical AND returns all documents that
$and
match the conditions of both clauses.

Inverts the effect of a query expression and returns documents that


$not
do not match the query expression.

Ajay Parashar IT@HCST Ajay Parashar IT@HCST

$or
QUERY DOCUMENTS
{ $or: [ { <expr1> }, { <expr2> }, ... , { <exprN> } ] }

• db.emp.find({$or: [{job: 'manager'}, {job: 'salesman'}]}) Specify “AND” Conditions

$and
{ $and: [ { <expr1> }, { <expr2> }, ... , { <exprN> } ] } Specify “OR” Conditions

• db.emp.find({$and: [{job:'manager'}, {sal:3400}]})

Specify “AND” as well as “OR” Conditions


$not
{ field: { $not: { <operator-expression> } } }

• db.emp.find({ job: {$not: {$eq: 'manager'}}})

Ajay Parashar IT@HCST Ajay Parashar IT@HCST


SPECIFY “AND” CONDITIONS SPECIFY “OR” CONDITIONS

Ajay Parashar IT@HCST Ajay Parashar IT@HCST

SPECIFY “AND” AS WELL AS “OR” CONDITIONS UPDATES DOCUMENTS

Single Update Updates a single


document within the
collection based on
the filter.

Ajay Parashar IT@HCST Ajay Parashar IT@HCST


UPDATES DOCUMENTS
• SQL Server
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

• MySQL
UPDATE table_name
SET
column_name1 = expr1,
column_name2 = expr2,
...
WHERE condition;
Ajay Parashar IT@HCST Ajay Parashar IT@HCST

UPDATES DOCUMENTS UPDATES DOCUMENTS

Multiple Update
Updates all documents
that match the specified
filter for a collection.

Ajay Parashar IT@HCST Ajay Parashar IT@HCST


UPDATES DOCUMENTS UPDATES DOCUMENTS

Replace One
Replaces a single
document within the
collection based on the
filter.

Ajay Parashar IT@HCST Ajay Parashar IT@HCST

DELETE DOCUMENTS
• SQL Server
DELETE FROM table_name WHERE condition;
Single Delete

• MySQL
DELETE FROM table_name WHERE condition;

Ajay Parashar IT@HCST Ajay Parashar IT@HCST


DELETE DOCUMENTS DELETE DOCUMENTS

Multiple Delete

Ajay Parashar IT@HCST Ajay Parashar IT@HCST

DELETE DOCUMENTS

Thank You!

Ajay Parashar IT@HCST Ajay Parashar IT@HCST

You might also like