SlideShare a Scribd company logo
MongoDB
Gyanendra Yadav
Jindal Steel & Power Ltd.
NoSQL Database
An Introduction
What is NoSQL?
 A form of Database Management System that is non relational
 System are schema less, avoid joins and are easy to scale.
NoSQL and Not Only SQL describe an approach to database design that
implements a key-value store, document store, column store or graph format for
data. It is an alternative to the Structured Query Language (SQL) database
prevalent beginning in the 1980s. NoSQL contrasts to databases that adhere to
SQL's relational methods, where data are placed in tables and data schema are
carefully designed before the database is built. NoSQL databases especially
target large sets of distributed data.
The Benefits of NoSQL
When compared to relational databases, NoSQL databases are more scalable and
provide superior performance, and their data model addresses several issues that
the relational model is not designed to address:
 Large volumes of rapidly changing structured, semi-structured, and
unstructured data
 Agile sprints, quick schema iteration, and frequent code pushes
 Object-oriented programming that is easy to use and flexible
 Geographically distributed scale-out architecture instead of expensive,
monolithic architecture
NoSQL vs. SQL Summary
SQL Databases NOSQL Databases
Types One type (SQL database) with minor variations Many different types including key-value
stores, document databases, wide-column
stores, and graph databases
Development History Developed in 1970s to deal with first wave of data storage
applications
Developed in late 2000s to deal with
limitations of SQL databases, especially
scalability, multi-structured data, geo-
distribution and agile development sprints
Examples MySQL, Postgres, Microsoft SQL Server, Oracle Database MongoDB, Cassandra, HBase, Neo4j
Data Storage Model Data stores in multiple columnar fashion in a table only two columns ('key' and 'value')
Schemas Structure and data types are fixed in advance and to store new
data entirely database altered, during which time the database
must be taken offline.
Fully Dynamic, with some enforcing data
validation rules
Scaling Typically vertical scaling is easy but Horizontal Scaling results
validation rules failure like FK.
Simply Horizontal Scaling is possible.
Development Model Mix of open-source Open-source
Supports Transactions Yes In certain circumstances
Comparison of RDMS & MongoDB
RDBMS MongoDB
Database Database
Table Collection
Tuple/Row Document
Column Field
Table Join Embedded Documents
Primary Key Primary Key (Default key _id provided by mongodb itself)
Database Server and Client
Mysqld/Oracle mongod
mysql/sqlplus mongo
What is MongoDB
MongoDB is an open-source document database that provides high
performance, high availability, and automatic scaling.
 The advantages of using documents are:
• Documents (i.e. objects) correspond to native data types in many programming languages.
• Embedded documents and arrays reduce need for expensive joins.
• Dynamic schema supports fluent polymorphism.
Key Features of MongoDB
 High Performance [Embedded data model reduce I/O Activity, Index support make query faster ]
 Rich Query Language [Data aggregation, Text Search & Geospatial Query]
 High Availability [Replica Set provide automatic Failure & data redundancy]
 Horizontal Scalability [Horizontal Scalability through Sharding (Also Support for zones)]
 Support for Multiple Storage Engines [Like MySql has Storage engine support]
Replication
Sharding
Document
 MongoDB stores data records as BSON documents. BSON is
a binary representation of JSON documents, though it
contains more data types than JSON
Document Structure
 The key decision in designing data models for MongoDB applications revolves around
the structure of documents and how the application represents relationships
between data. There are two tools that allow applications to represent these
relationships: references and embedded documents.
References: (Normalized data models.)
Embedded Data: (denormalized data models allow applications to retrieve
and manipulate related data in a single database operation)
Which One is Better?
• In general, use embedded data models when:
• you have “contains” relationships between entities.
• you have one-to-many relationships between entities. In these relationships the “many” or
child documents always appear with or are viewed in the context of the “one” or parent
documents.
• In general, use normalized data models:
• when embedding would result in duplication of data but would not provide sufficient
read performance advantages to outweigh the implications of the duplication.
• to represent more complex many-to-many relationships.
• to model large hierarchical data sets.
Embedded Normalized
Better performance for read operations More flexibility than embedding
Single atomic read/write operation Client-side applications must issue follow-up queries to
resolve the references
Require more round trips to the server
 var mydoc = {
 _id: ObjectId("5099803df3f4948bd2f98391"),
 name: { first: "Alan", last: "Turing" },
 birth: new Date('Jun 23, 1912'),
 death: new Date('Jun 07, 1954'),
 contribs: [ "Turing machine", "Turing test", "Turingery" ],
 views : NumberLong(1250000)
 }
 The above fields have the following data types:
• _id holds an ObjectId.
• name holds an embedded document that contains the fields first and last.
• birth and death hold values of the Date type.
• contribs holds an array of strings.
• views holds a value of the NumberLong type.
 Field Names
Documents have the following restrictions on field names:
• The field name _id is reserved for use as a primary key; its value
must be unique in the collection, is immutable, and may be of any
type other than an array.
• The field names cannot start with the dollar sign ($) character.
• The field names cannot contain the dot (.) character.
• The field names cannot contain the null character.
 Dot Notation
• MongoDB uses the dot notation to access the elements of an array and to
access the fields of an embedded document.
<array>.<index>, "<embedded document>.<field>"
Ex. contribs.2
 The _id Field
The _id field has the following behavior and constraints:
• By default, MongoDB creates a unique index on the _id field during the creation of a
collection.
• The _id field is always the first field in the documents. If the server receives a
document that does not have the _id field first, then the server will move the field
to the beginning.
• The _id field may contain values of any BSON data type, other than an array.
 ObjectId
ObjectIds are small, likely unique, fast to generate, and ordered. ObjectId values
consists of 12-bytes, where the first four bytes are a timestamp that reflect the
ObjectId’s creation, specifically:
• a 4-byte value representing the seconds since the Unix epoch,
• a 3-byte machine identifier,
• a 2-byte process id, and
• a 3-byte counter, starting with a random value.
Key Points of Schema Design in MongoDB
 Design your schema according to user requirements.
 Combine objects into one document if you will use them together. Otherwise
separate them (but make sure there should not be need of joins).
 Duplicate the data (but limited) because disk space is cheap as compare to
compute time.
 Do joins while write, not on read.
 Optimize your schema for most frequent use cases.
 Do complex aggregation in the schema.
Install MongoDB on Ubuntu
 Import the public key used by the package management system.
 The Ubuntu package management tools (i.e. dpkg and apt) ensure package
consistency and authenticity by requiring that distributors sign packages with GPG
keys. Issue the following command to import the MongoDB public GPG Key
 sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
 Create a list file for MongoDB.
 Create the /etc/apt/sources.list.d/mongodb-org-3.0.list list file using the
command appropriate for your version of Ubuntu:
 echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.0
multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list
 Reload local package database
 Issue the following command to reload the local package database:
 sudo apt-get update
Install MongoDB on Ubuntu continue....
 Install the MongoDB packages.
 Install the latest stable version of MongoDB
 You can install either the latest stable version of MongoDB or a specific version of
MongoDB.
 sudo apt-get install -y mongodb-org
 Install a specific release of MongoDB.
 To install a specific release, you must specify each component package individually along
with the version number, as in the following example:
 sudo apt-get install -y mongodb-org=3.0.15 mongodb-org-server=3.0.15 mongodb-org-
shell=3.0.15 mongodb-org-mongos=3.0.15 mongodb-org-tools=3.0.15
Database Operation
 If there is no existing database, the following command is used to create a
new database.
>use jisl
 Note: If the database already exists, it will return the existing database.
 To check the currently selected database, use the command db:
>db
 To check the database list, use the command show dbs:
 >show dbs
 dropDatabase command is used to drop a database. It also deletes the
associated data files
>db.dropDatabase()
Collection Operation
 To create Collection
>db.createCollection(“user")
 To check the created collection
>show collections
 To Drop the created collection
>db.user.drop()
MongoDB CRUD Operations
 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.
 Read Operations
 Read operations retrieves documents from a collection; i.e. queries a collection for
documents
 Update Operations
 Update operations modify existing documents in a collection.
 Delete Operations
 Delete operations remove documents from a collection.
 Bulk Write
 MongoDB provides the ability to perform write operations in bulk.(Not covered in this PPT)
Create Operations
 db.collection.insertOne()
 db.collection.insertMany()
 db.inventory.insertOne({ item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w:
35.5, uom: "cm" } })
 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" } }])
SQL INSERT Statements MongoDB insertOne() Statements
INSERT INTO people(user_id, age, status) VALUES ("bcd001", 45, "A") db.people.insertOne( { user_id: "bcd001", age: 45, status: "A" } )
Read Operations
 db.collection.find()
 Ex.
 In
 db.inventory.find( { status: { $in: [ "A", "D" ] } } )
 AND
 db.inventory.find( { status: "A", qty: { $lt: 30 } } )
 OR
 db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } )
 AND with OR: status equals "A" and either qty is less than ($lt) 30 or item starts with the character p
 db.inventory.find({status: "A", $or: [ { qty: { $lt: 30 } }, { item: /^p/ } ]})
SQL SELECT Statements MongoDB find() Statements
SELECT * FROM people db.people.find()
SELECT id, user_id, status FROM people db.people.find( { }, { user_id: 1, status: 1 } )
SELECT user_id, status FROM people db.people.find( { }, { user_id: 1, status: 1, _id: 0 } )
SELECT * FROM people WHERE status = "A" db.people.find( { status: "A" } )
SELECT user_id, status FROM people WHERE status = "A" db.people.find( { status: "A" }, { user_id: 1, status: 1, _id: 0 } )
SELECT * FROM people WHERE status != "A" db.people.find( { status: { $ne: "A" } } )
SELECT * FROM people WHERE status = "A" AND age = 50 db.people.find( { status: "A", age: 50 } )
SELECT * FROM people WHERE status = "A" OR age = 50 db.people.find( { $or: [ { status: "A" } , { age: 50 } ] } )
SELECT * FROM people WHERE age > 25 db.people.find( { age: { $gt: 25 } } )
SELECT * FROM people WHERE age < 25 db.people.find( { age: { $lt: 25 } } )
SELECT * FROM people WHERE age > 25 AND age <= 50 db.people.find( { age: { $gt: 25, $lte: 50 } } )
SELECT * FROM people WHERE user_id like "%bc%"
db.people.find( { user_id: /bc/ } )
-or-
db.people.find( { user_id: { $regex: /bc/ } } )
SELECT * FROM people WHERE user_id like "bc%"
db.people.find( { user_id: /^bc/ } )
-or-
db.people.find( { user_id: { $regex: /^bc/ } } )
SELECT * FROM people WHERE status = "A" ORDER BY user_id ASC db.people.find( { status: "A" } ).sort( { user_id: 1 } )
SELECT * FROM people WHERE status = "A" ORDER BY user_id DESC db.people.find( { status: "A" } ).sort( { user_id: -1 } )
SELECT COUNT(*) FROM people
db.people.count()
or
db.people.find().count()
SELECT COUNT(user_id) FROM people
db.people.count( { user_id: { $exists: true } } )
or
db.people.find( { user_id: { $exists: true } } ).count()
SELECT COUNT(*) FROM people WHERE age > 30
db.people.count( { age: { $gt: 30 } } )
or
db.people.find( { age: { $gt: 30 } } ).count()
SELECT DISTINCT(status) FROM people db.people.distinct( "status" )
SELECT * FROM people LIMIT 1
db.people.findOne()
or
db.people.find().limit(1)
SELECT * FROM people LIMIT 5 SKIP 10 db.people.find().limit(5).skip(10)
EXPLAIN SELECT * FROM people WHERE status = "A" db.people.find( { status: "A" } ).explain()
Update Operations
 db.collection.updateOne()
 db.collection.updateMany()
 db.collection.replaceOne()
 db.collection.updateOne()
db.inventory.updateOne({ item: "paper" }
,{$set:
{ "size.uom": "cm", status: "P" }
,$currentDate: { lastModified: true }
})
SQL Update Statements MongoDB updateMany() Statements
UPDATE people SET status = "C" WHERE age > 25 db.people.updateMany( { age: { $gt: 25 } }, { $set: { status: "C" } } )
UPDATE people SET age = age + 3 WHERE status = "A" db.people.updateMany( { status: "A" } , { $inc: { age: 3 } } )
Delete Operations
 db.collection.deleteOne()
 db.collection.deleteMany()
 db.collection.deleteOne(): It will delete first occurance
db.inventory.deleteOne( { status: "D" } )
 db.collection.deleteMany()
db.inventory.deleteMany( { status: "D" } )
 Note:
Indexes: Delete operations do not drop indexes, even if deleting all documents
from a collection.
SQL Delete Statements MongoDB deleteMany() Statements
DELETE FROM people WHERE status = "D" db.people.deleteMany( { status: "D" } )
DELETE FROM people db.people.deleteMany({})
Thank You……
 Impotent Reference link:
 https://docs.mongodb.com/manual
TODO Next...
 MongoDB Integration With Spring (CURD Application).
 MongoBD Administration.
 MongoDB Replication.
 MongoDB Sharding.
 MongoDB Data Models
 MongoDB Constratints and Data Validation

More Related Content

What's hot

Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
NodeXperts
 
Basics of MongoDB
Basics of MongoDB Basics of MongoDB
Basics of MongoDB
Habilelabs
 
NOSQL and MongoDB Database
NOSQL and MongoDB DatabaseNOSQL and MongoDB Database
NOSQL and MongoDB Database
Tariqul islam
 
Mongo DB Presentation
Mongo DB PresentationMongo DB Presentation
Mongo DB Presentation
Jaya Naresh Kovela
 
An introduction to MongoDB
An introduction to MongoDBAn introduction to MongoDB
An introduction to MongoDB
Universidade de São Paulo
 
Mongodb basics and architecture
Mongodb basics and architectureMongodb basics and architecture
Mongodb basics and architecture
Bishal Khanal
 
Introduction to MongoDB and CRUD operations
Introduction to MongoDB and CRUD operationsIntroduction to MongoDB and CRUD operations
Introduction to MongoDB and CRUD operations
Anand Kumar
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
Mike Dirolf
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
Jeff Fox
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
MongoDB
 
Spring boot
Spring bootSpring boot
Spring boot
sdeeg
 
Mongo Nosql CRUD Operations
Mongo Nosql CRUD OperationsMongo Nosql CRUD Operations
Mongo Nosql CRUD Operations
anujaggarwal49
 
Mongo db dhruba
Mongo db dhrubaMongo db dhruba
Mongo db dhruba
Dhrubaji Mandal ♛
 
Mongodb
MongodbMongodb
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
Dineesha Suraweera
 
NoSql
NoSqlNoSql
Introduction to NoSQL Databases
Introduction to NoSQL DatabasesIntroduction to NoSQL Databases
Introduction to NoSQL DatabasesDerek Stainer
 
MongoDB Fundamentals
MongoDB FundamentalsMongoDB Fundamentals
MongoDB Fundamentals
MongoDB
 
ReactJS presentation.pptx
ReactJS presentation.pptxReactJS presentation.pptx
ReactJS presentation.pptx
DivyanshGupta922023
 

What's hot (20)

Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
MongoDB
MongoDBMongoDB
MongoDB
 
Basics of MongoDB
Basics of MongoDB Basics of MongoDB
Basics of MongoDB
 
NOSQL and MongoDB Database
NOSQL and MongoDB DatabaseNOSQL and MongoDB Database
NOSQL and MongoDB Database
 
Mongo DB Presentation
Mongo DB PresentationMongo DB Presentation
Mongo DB Presentation
 
An introduction to MongoDB
An introduction to MongoDBAn introduction to MongoDB
An introduction to MongoDB
 
Mongodb basics and architecture
Mongodb basics and architectureMongodb basics and architecture
Mongodb basics and architecture
 
Introduction to MongoDB and CRUD operations
Introduction to MongoDB and CRUD operationsIntroduction to MongoDB and CRUD operations
Introduction to MongoDB and CRUD operations
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
Spring boot
Spring bootSpring boot
Spring boot
 
Mongo Nosql CRUD Operations
Mongo Nosql CRUD OperationsMongo Nosql CRUD Operations
Mongo Nosql CRUD Operations
 
Mongo db dhruba
Mongo db dhrubaMongo db dhruba
Mongo db dhruba
 
Mongodb
MongodbMongodb
Mongodb
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
NoSql
NoSqlNoSql
NoSql
 
Introduction to NoSQL Databases
Introduction to NoSQL DatabasesIntroduction to NoSQL Databases
Introduction to NoSQL Databases
 
MongoDB Fundamentals
MongoDB FundamentalsMongoDB Fundamentals
MongoDB Fundamentals
 
ReactJS presentation.pptx
ReactJS presentation.pptxReactJS presentation.pptx
ReactJS presentation.pptx
 

Similar to Mongo db

Mongodb Introduction
Mongodb IntroductionMongodb Introduction
Mongodb Introduction
Raghvendra Parashar
 
MongoDB NoSQL database a deep dive -MyWhitePaper
MongoDB  NoSQL database a deep dive -MyWhitePaperMongoDB  NoSQL database a deep dive -MyWhitePaper
MongoDB NoSQL database a deep dive -MyWhitePaper
Rajesh Kumar
 
UNIT-1 MongoDB.pptx
UNIT-1 MongoDB.pptxUNIT-1 MongoDB.pptx
UNIT-1 MongoDB.pptx
DharaDarji5
 
Mongo Bb - NoSQL tutorial
Mongo Bb - NoSQL tutorialMongo Bb - NoSQL tutorial
Mongo Bb - NoSQL tutorial
Mohan Rathour
 
mongodb11 (1) (1).pptx
mongodb11 (1) (1).pptxmongodb11 (1) (1).pptx
mongodb11 (1) (1).pptx
RoopaR36
 
Top MongoDB interview Questions and Answers
Top MongoDB interview Questions and AnswersTop MongoDB interview Questions and Answers
Top MongoDB interview Questions and Answers
jeetendra mandal
 
Mongodb By Vipin
Mongodb By VipinMongodb By Vipin
Mongodb By Vipin
Vipin Mundayad
 
MongoDB - An Introduction
MongoDB - An IntroductionMongoDB - An Introduction
MongoDB - An Introduction
dinkar thakur
 
Mongodb
MongodbMongodb
Mongodb
Thiago Veiga
 
MongoDB - An Introduction
MongoDB - An IntroductionMongoDB - An Introduction
MongoDB - An Introduction
sethfloydjr
 
Mongo db basics
Mongo db basicsMongo db basics
Mongo db basics
Claudio Montoya
 
3-Mongodb and Mapreduce Programming.pdf
3-Mongodb and Mapreduce Programming.pdf3-Mongodb and Mapreduce Programming.pdf
3-Mongodb and Mapreduce Programming.pdf
MarianJRuben
 
Introduction to MongoDB and its best practices
Introduction to MongoDB and its best practicesIntroduction to MongoDB and its best practices
Introduction to MongoDB and its best practices
AshishRathore72
 
No SQL - MongoDB
No SQL - MongoDBNo SQL - MongoDB
No SQL - MongoDB
Mirza Asif
 
MongoDB
MongoDBMongoDB
MongoDB
wiTTyMinds1
 
Kalp Corporate MongoDB Tutorials
Kalp Corporate MongoDB TutorialsKalp Corporate MongoDB Tutorials
Kalp Corporate MongoDB Tutorials
Kalp Corporate
 
MongoDB using Grails plugin by puneet behl
MongoDB using Grails plugin by puneet behlMongoDB using Grails plugin by puneet behl
MongoDB using Grails plugin by puneet behl
TO THE NEW | Technology
 
Mongo DB
Mongo DBMongo DB
Mongodb - NoSql Database
Mongodb - NoSql DatabaseMongodb - NoSql Database
Mongodb - NoSql Database
Prashant Gupta
 
MongoDB.pptx
MongoDB.pptxMongoDB.pptx
MongoDB.pptx
Aayush Chimaniya
 

Similar to Mongo db (20)

Mongodb Introduction
Mongodb IntroductionMongodb Introduction
Mongodb Introduction
 
MongoDB NoSQL database a deep dive -MyWhitePaper
MongoDB  NoSQL database a deep dive -MyWhitePaperMongoDB  NoSQL database a deep dive -MyWhitePaper
MongoDB NoSQL database a deep dive -MyWhitePaper
 
UNIT-1 MongoDB.pptx
UNIT-1 MongoDB.pptxUNIT-1 MongoDB.pptx
UNIT-1 MongoDB.pptx
 
Mongo Bb - NoSQL tutorial
Mongo Bb - NoSQL tutorialMongo Bb - NoSQL tutorial
Mongo Bb - NoSQL tutorial
 
mongodb11 (1) (1).pptx
mongodb11 (1) (1).pptxmongodb11 (1) (1).pptx
mongodb11 (1) (1).pptx
 
Top MongoDB interview Questions and Answers
Top MongoDB interview Questions and AnswersTop MongoDB interview Questions and Answers
Top MongoDB interview Questions and Answers
 
Mongodb By Vipin
Mongodb By VipinMongodb By Vipin
Mongodb By Vipin
 
MongoDB - An Introduction
MongoDB - An IntroductionMongoDB - An Introduction
MongoDB - An Introduction
 
Mongodb
MongodbMongodb
Mongodb
 
MongoDB - An Introduction
MongoDB - An IntroductionMongoDB - An Introduction
MongoDB - An Introduction
 
Mongo db basics
Mongo db basicsMongo db basics
Mongo db basics
 
3-Mongodb and Mapreduce Programming.pdf
3-Mongodb and Mapreduce Programming.pdf3-Mongodb and Mapreduce Programming.pdf
3-Mongodb and Mapreduce Programming.pdf
 
Introduction to MongoDB and its best practices
Introduction to MongoDB and its best practicesIntroduction to MongoDB and its best practices
Introduction to MongoDB and its best practices
 
No SQL - MongoDB
No SQL - MongoDBNo SQL - MongoDB
No SQL - MongoDB
 
MongoDB
MongoDBMongoDB
MongoDB
 
Kalp Corporate MongoDB Tutorials
Kalp Corporate MongoDB TutorialsKalp Corporate MongoDB Tutorials
Kalp Corporate MongoDB Tutorials
 
MongoDB using Grails plugin by puneet behl
MongoDB using Grails plugin by puneet behlMongoDB using Grails plugin by puneet behl
MongoDB using Grails plugin by puneet behl
 
Mongo DB
Mongo DBMongo DB
Mongo DB
 
Mongodb - NoSql Database
Mongodb - NoSql DatabaseMongodb - NoSql Database
Mongodb - NoSql Database
 
MongoDB.pptx
MongoDB.pptxMongoDB.pptx
MongoDB.pptx
 

Recently uploaded

Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
LIGA(E)11111111111111111111111111111111111111111.ppt
LIGA(E)11111111111111111111111111111111111111111.pptLIGA(E)11111111111111111111111111111111111111111.ppt
LIGA(E)11111111111111111111111111111111111111111.ppt
ssuser9bd3ba
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
seandesed
 
Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.
PrashantGoswami42
 
Vaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdfVaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdf
Kamal Acharya
 
Halogenation process of chemical process industries
Halogenation process of chemical process industriesHalogenation process of chemical process industries
Halogenation process of chemical process industries
MuhammadTufail242431
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
bakpo1
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
Intella Parts
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Robbie Edward Sayers
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdf
Kamal Acharya
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
Pipe Restoration Solutions
 

Recently uploaded (20)

Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
LIGA(E)11111111111111111111111111111111111111111.ppt
LIGA(E)11111111111111111111111111111111111111111.pptLIGA(E)11111111111111111111111111111111111111111.ppt
LIGA(E)11111111111111111111111111111111111111111.ppt
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
 
Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.
 
Vaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdfVaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdf
 
Halogenation process of chemical process industries
Halogenation process of chemical process industriesHalogenation process of chemical process industries
Halogenation process of chemical process industries
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdf
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 

Mongo db

  • 1. MongoDB Gyanendra Yadav Jindal Steel & Power Ltd. NoSQL Database An Introduction
  • 2. What is NoSQL?  A form of Database Management System that is non relational  System are schema less, avoid joins and are easy to scale. NoSQL and Not Only SQL describe an approach to database design that implements a key-value store, document store, column store or graph format for data. It is an alternative to the Structured Query Language (SQL) database prevalent beginning in the 1980s. NoSQL contrasts to databases that adhere to SQL's relational methods, where data are placed in tables and data schema are carefully designed before the database is built. NoSQL databases especially target large sets of distributed data.
  • 3. The Benefits of NoSQL When compared to relational databases, NoSQL databases are more scalable and provide superior performance, and their data model addresses several issues that the relational model is not designed to address:  Large volumes of rapidly changing structured, semi-structured, and unstructured data  Agile sprints, quick schema iteration, and frequent code pushes  Object-oriented programming that is easy to use and flexible  Geographically distributed scale-out architecture instead of expensive, monolithic architecture
  • 4. NoSQL vs. SQL Summary SQL Databases NOSQL Databases Types One type (SQL database) with minor variations Many different types including key-value stores, document databases, wide-column stores, and graph databases Development History Developed in 1970s to deal with first wave of data storage applications Developed in late 2000s to deal with limitations of SQL databases, especially scalability, multi-structured data, geo- distribution and agile development sprints Examples MySQL, Postgres, Microsoft SQL Server, Oracle Database MongoDB, Cassandra, HBase, Neo4j Data Storage Model Data stores in multiple columnar fashion in a table only two columns ('key' and 'value') Schemas Structure and data types are fixed in advance and to store new data entirely database altered, during which time the database must be taken offline. Fully Dynamic, with some enforcing data validation rules Scaling Typically vertical scaling is easy but Horizontal Scaling results validation rules failure like FK. Simply Horizontal Scaling is possible. Development Model Mix of open-source Open-source Supports Transactions Yes In certain circumstances
  • 5. Comparison of RDMS & MongoDB RDBMS MongoDB Database Database Table Collection Tuple/Row Document Column Field Table Join Embedded Documents Primary Key Primary Key (Default key _id provided by mongodb itself) Database Server and Client Mysqld/Oracle mongod mysql/sqlplus mongo
  • 6. What is MongoDB MongoDB is an open-source document database that provides high performance, high availability, and automatic scaling.  The advantages of using documents are: • Documents (i.e. objects) correspond to native data types in many programming languages. • Embedded documents and arrays reduce need for expensive joins. • Dynamic schema supports fluent polymorphism. Key Features of MongoDB  High Performance [Embedded data model reduce I/O Activity, Index support make query faster ]  Rich Query Language [Data aggregation, Text Search & Geospatial Query]  High Availability [Replica Set provide automatic Failure & data redundancy]  Horizontal Scalability [Horizontal Scalability through Sharding (Also Support for zones)]  Support for Multiple Storage Engines [Like MySql has Storage engine support]
  • 9. Document  MongoDB stores data records as BSON documents. BSON is a binary representation of JSON documents, though it contains more data types than JSON
  • 10. Document Structure  The key decision in designing data models for MongoDB applications revolves around the structure of documents and how the application represents relationships between data. There are two tools that allow applications to represent these relationships: references and embedded documents. References: (Normalized data models.)
  • 11. Embedded Data: (denormalized data models allow applications to retrieve and manipulate related data in a single database operation)
  • 12. Which One is Better? • In general, use embedded data models when: • you have “contains” relationships between entities. • you have one-to-many relationships between entities. In these relationships the “many” or child documents always appear with or are viewed in the context of the “one” or parent documents. • In general, use normalized data models: • when embedding would result in duplication of data but would not provide sufficient read performance advantages to outweigh the implications of the duplication. • to represent more complex many-to-many relationships. • to model large hierarchical data sets. Embedded Normalized Better performance for read operations More flexibility than embedding Single atomic read/write operation Client-side applications must issue follow-up queries to resolve the references Require more round trips to the server
  • 13.  var mydoc = {  _id: ObjectId("5099803df3f4948bd2f98391"),  name: { first: "Alan", last: "Turing" },  birth: new Date('Jun 23, 1912'),  death: new Date('Jun 07, 1954'),  contribs: [ "Turing machine", "Turing test", "Turingery" ],  views : NumberLong(1250000)  }  The above fields have the following data types: • _id holds an ObjectId. • name holds an embedded document that contains the fields first and last. • birth and death hold values of the Date type. • contribs holds an array of strings. • views holds a value of the NumberLong type.
  • 14.  Field Names Documents have the following restrictions on field names: • The field name _id is reserved for use as a primary key; its value must be unique in the collection, is immutable, and may be of any type other than an array. • The field names cannot start with the dollar sign ($) character. • The field names cannot contain the dot (.) character. • The field names cannot contain the null character.  Dot Notation • MongoDB uses the dot notation to access the elements of an array and to access the fields of an embedded document. <array>.<index>, "<embedded document>.<field>" Ex. contribs.2
  • 15.  The _id Field The _id field has the following behavior and constraints: • By default, MongoDB creates a unique index on the _id field during the creation of a collection. • The _id field is always the first field in the documents. If the server receives a document that does not have the _id field first, then the server will move the field to the beginning. • The _id field may contain values of any BSON data type, other than an array.  ObjectId ObjectIds are small, likely unique, fast to generate, and ordered. ObjectId values consists of 12-bytes, where the first four bytes are a timestamp that reflect the ObjectId’s creation, specifically: • a 4-byte value representing the seconds since the Unix epoch, • a 3-byte machine identifier, • a 2-byte process id, and • a 3-byte counter, starting with a random value.
  • 16. Key Points of Schema Design in MongoDB  Design your schema according to user requirements.  Combine objects into one document if you will use them together. Otherwise separate them (but make sure there should not be need of joins).  Duplicate the data (but limited) because disk space is cheap as compare to compute time.  Do joins while write, not on read.  Optimize your schema for most frequent use cases.  Do complex aggregation in the schema.
  • 17. Install MongoDB on Ubuntu  Import the public key used by the package management system.  The Ubuntu package management tools (i.e. dpkg and apt) ensure package consistency and authenticity by requiring that distributors sign packages with GPG keys. Issue the following command to import the MongoDB public GPG Key  sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10  Create a list file for MongoDB.  Create the /etc/apt/sources.list.d/mongodb-org-3.0.list list file using the command appropriate for your version of Ubuntu:  echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list  Reload local package database  Issue the following command to reload the local package database:  sudo apt-get update
  • 18. Install MongoDB on Ubuntu continue....  Install the MongoDB packages.  Install the latest stable version of MongoDB  You can install either the latest stable version of MongoDB or a specific version of MongoDB.  sudo apt-get install -y mongodb-org  Install a specific release of MongoDB.  To install a specific release, you must specify each component package individually along with the version number, as in the following example:  sudo apt-get install -y mongodb-org=3.0.15 mongodb-org-server=3.0.15 mongodb-org- shell=3.0.15 mongodb-org-mongos=3.0.15 mongodb-org-tools=3.0.15
  • 19. Database Operation  If there is no existing database, the following command is used to create a new database. >use jisl  Note: If the database already exists, it will return the existing database.  To check the currently selected database, use the command db: >db  To check the database list, use the command show dbs:  >show dbs  dropDatabase command is used to drop a database. It also deletes the associated data files >db.dropDatabase()
  • 20. Collection Operation  To create Collection >db.createCollection(“user")  To check the created collection >show collections  To Drop the created collection >db.user.drop()
  • 21. MongoDB CRUD Operations  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.  Read Operations  Read operations retrieves documents from a collection; i.e. queries a collection for documents  Update Operations  Update operations modify existing documents in a collection.  Delete Operations  Delete operations remove documents from a collection.  Bulk Write  MongoDB provides the ability to perform write operations in bulk.(Not covered in this PPT)
  • 22. Create Operations  db.collection.insertOne()  db.collection.insertMany()  db.inventory.insertOne({ item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } })  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" } }]) SQL INSERT Statements MongoDB insertOne() Statements INSERT INTO people(user_id, age, status) VALUES ("bcd001", 45, "A") db.people.insertOne( { user_id: "bcd001", age: 45, status: "A" } )
  • 23. Read Operations  db.collection.find()  Ex.  In  db.inventory.find( { status: { $in: [ "A", "D" ] } } )  AND  db.inventory.find( { status: "A", qty: { $lt: 30 } } )  OR  db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } )  AND with OR: status equals "A" and either qty is less than ($lt) 30 or item starts with the character p  db.inventory.find({status: "A", $or: [ { qty: { $lt: 30 } }, { item: /^p/ } ]})
  • 24. SQL SELECT Statements MongoDB find() Statements SELECT * FROM people db.people.find() SELECT id, user_id, status FROM people db.people.find( { }, { user_id: 1, status: 1 } ) SELECT user_id, status FROM people db.people.find( { }, { user_id: 1, status: 1, _id: 0 } ) SELECT * FROM people WHERE status = "A" db.people.find( { status: "A" } ) SELECT user_id, status FROM people WHERE status = "A" db.people.find( { status: "A" }, { user_id: 1, status: 1, _id: 0 } ) SELECT * FROM people WHERE status != "A" db.people.find( { status: { $ne: "A" } } ) SELECT * FROM people WHERE status = "A" AND age = 50 db.people.find( { status: "A", age: 50 } ) SELECT * FROM people WHERE status = "A" OR age = 50 db.people.find( { $or: [ { status: "A" } , { age: 50 } ] } )
  • 25. SELECT * FROM people WHERE age > 25 db.people.find( { age: { $gt: 25 } } ) SELECT * FROM people WHERE age < 25 db.people.find( { age: { $lt: 25 } } ) SELECT * FROM people WHERE age > 25 AND age <= 50 db.people.find( { age: { $gt: 25, $lte: 50 } } ) SELECT * FROM people WHERE user_id like "%bc%" db.people.find( { user_id: /bc/ } ) -or- db.people.find( { user_id: { $regex: /bc/ } } ) SELECT * FROM people WHERE user_id like "bc%" db.people.find( { user_id: /^bc/ } ) -or- db.people.find( { user_id: { $regex: /^bc/ } } ) SELECT * FROM people WHERE status = "A" ORDER BY user_id ASC db.people.find( { status: "A" } ).sort( { user_id: 1 } ) SELECT * FROM people WHERE status = "A" ORDER BY user_id DESC db.people.find( { status: "A" } ).sort( { user_id: -1 } ) SELECT COUNT(*) FROM people db.people.count() or db.people.find().count() SELECT COUNT(user_id) FROM people db.people.count( { user_id: { $exists: true } } ) or db.people.find( { user_id: { $exists: true } } ).count() SELECT COUNT(*) FROM people WHERE age > 30 db.people.count( { age: { $gt: 30 } } ) or db.people.find( { age: { $gt: 30 } } ).count() SELECT DISTINCT(status) FROM people db.people.distinct( "status" ) SELECT * FROM people LIMIT 1 db.people.findOne() or db.people.find().limit(1) SELECT * FROM people LIMIT 5 SKIP 10 db.people.find().limit(5).skip(10) EXPLAIN SELECT * FROM people WHERE status = "A" db.people.find( { status: "A" } ).explain()
  • 26. Update Operations  db.collection.updateOne()  db.collection.updateMany()  db.collection.replaceOne()  db.collection.updateOne() db.inventory.updateOne({ item: "paper" } ,{$set: { "size.uom": "cm", status: "P" } ,$currentDate: { lastModified: true } }) SQL Update Statements MongoDB updateMany() Statements UPDATE people SET status = "C" WHERE age > 25 db.people.updateMany( { age: { $gt: 25 } }, { $set: { status: "C" } } ) UPDATE people SET age = age + 3 WHERE status = "A" db.people.updateMany( { status: "A" } , { $inc: { age: 3 } } )
  • 27. Delete Operations  db.collection.deleteOne()  db.collection.deleteMany()  db.collection.deleteOne(): It will delete first occurance db.inventory.deleteOne( { status: "D" } )  db.collection.deleteMany() db.inventory.deleteMany( { status: "D" } )  Note: Indexes: Delete operations do not drop indexes, even if deleting all documents from a collection. SQL Delete Statements MongoDB deleteMany() Statements DELETE FROM people WHERE status = "D" db.people.deleteMany( { status: "D" } ) DELETE FROM people db.people.deleteMany({})
  • 28. Thank You……  Impotent Reference link:  https://docs.mongodb.com/manual TODO Next...  MongoDB Integration With Spring (CURD Application).  MongoBD Administration.  MongoDB Replication.  MongoDB Sharding.  MongoDB Data Models  MongoDB Constratints and Data Validation