SlideShare a Scribd company logo
MongoDB
Outline
 Introduction
 Overview of MongoDB’s Documents, Collections and Databases
 Comparison of RDBMS and MongoDB
 More on ObjectID
 MongoDB Datatypes
 Document Sample
 MongoDB Advantages and where to use it
 Create and Drop for Collections, Documents and Databases
 CRUD Operations for Documents
 Relations in MongoDB
 Projection
 Limiting, Sorting and Indexing in MongoDB
 Replication and Sharding in Mongo DB
 Companies that use MongoDB
MongoDB is an open-source document database
and leading NoSQL database. MongoDB is written
mostly in C++.
Released in 2009
Initial Release
Document Based
Types of NoSQL Databases:
• Document-Based
• Key-value stores
• Wide Column
• Graph
NoSQL Humongous
Scalable & Reliable
Cross-Platform
Available on Different Platforms
Overview
 Database
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
Collection is a group of MongoDB documents. It is the equivalent of an RDBMS
table. A collection exists within a single database. 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.
 Document
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 vs 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
Advantages
 Schema less − MongoDB is a document database in which one collection holds
different documents. Number of fields, content and size of the document can
differ from one document to another.
 Structure of a single object is clear.
 No complex joins.
 Deep query-ability. MongoDB supports dynamic queries on documents using a
document-based query language that's nearly as powerful as SQL.
 Tuning.
 Ease of scale-out − MongoDB is easy to scale.
 Uses internal memory for storing the (windowed) working set, enabling faster
access of data.
Why MongoDB?
 Document Oriented Storage − Data is stored in the form of JSON style
documents.
 Index on any attribute
 Replication and high availability
 Auto-Sharding
 Rich queries
 Fast in-place updates
Where to Use MongoDB?
 Big Data
 Content Management and Delivery
 Mobile and Social Infrastructure
 User Data Management
 Data Hub
Sample Document
{
"_id" : ObjectId("5ecb9ea70403c0aa6001b4a2"),
"brand" : "BMW",
"model" : "X5",
"tier" : "B",
"max_speed" : 220,
"color" : "Black",
"airbags" : [
"front-seats",
"back-seats",
"other places"
]
}
_id is 12 bytes hexadecimal number
unique for every document in a
collection. You can provide it
yourself too!
ObjectID
 An ObjectId is a 12-byte BSON type having the following structure
 Generate By mongoDB
>newObjectId = ObjectId()  ObjectId("5349b4ddd2781d08c09890f3")
 Generate By us
>myObjectId = ObjectId("5349b4ddd2781d08c09890f4")
Datatypes
 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.
 Boolean − This type is used to store a boolean (true/ false) value.
 Double − This type is used to store floating point values.
 Min/ Max keys − This type is used to compare a value against the lowest and highest BSON elements.
 Arrays − This type is used to store arrays or list or multiple values into one key.
 Timestamp − ctimestamp. This can be handy for recording when a document has been modified or added.
 Object − This datatype is used for embedded documents.
 Null − This type is used to store a Null value.
 Symbol − This datatype is used identically to a string; however, it's generally reserved for languages that use a specific
symbol type.
 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.
 Object ID − This datatype is used to store the document’s ID.
 Binary data − This datatype is used to store binary data.
 Code − This datatype is used to store JavaScript code into the document.
 Regular expression − This datatype is used to store regular expression.
Create & Drop Database
 MongoDB use DATABASE_NAME is used to create database. The command will
create a new database if it doesn't exist, otherwise it will return the existing
database.
 MongoDB db.dropDatabase() command is used to drop a existing database.
Example:
use divarDB
db.dropDatabase()
 If you want to check your databases list, use the command show dbs.
Create Collections
 MongoDB db.createCollection(name, options) is used to create collection.
db.createCollection("mycol", { capped : true, autoIndexID : true, size : 6142800,
max : 10000 } )
Parameter Type
Name String
Options Document
Field Type Description
capped Boolean
If true, enables a capped collection. Capped
collection is a fixed size collection that
automatically overwrites its oldest entries when
it reaches its maximum size. If you specify true,
you need to specify size parameter also.
autoIn
dexId
Boolean
If true, automatically create index on _id fields.
size number
Specifies a maximum size in bytes for a capped
collection. If capped is true, then you need to
specify this field also.
max number
Specifies the maximum number of documents
allowed in the capped collection.
Drop Collections
 MongoDB's db.collection.drop() is used to drop a collection from the
database.
 show collections is used to show all collections in the current
Example:
db.mycollection.drop()
Insert Document
 To insert data into MongoDB collection, you need to use
MongoDB's insert() or save() method.
 If you need to insert only one document you can use insertOne() method.
 You can insert multiple documents using the insertMany() method. To this method you
need to pass an array of documents.
Example:
db.stuff.insert({ title: "MongoDB Insert Docs", description: "MongoDB is no sql database",
tags: ['mongodb', 'database', 'NoSQL'], likes: 100 })
db.presenters.insertMany([
{
First_Name: “Shayan",
Last_Name: “Daneshvar",
},
{
First_Name: “Hashem",
Last_Name: “Pourallahverdi",
}])
Query Document
how to query document from MongoDB collection.
 The find() Method
 The pretty() Method
 The findOne() method
 AND
 OR
 NOR
 NOT
Operation Syntax Example RDBM S Equivalent
Equality {<key>:{$eg;<value>}} db.mycol.find({"by":"kntu"}).pretty() where by = 'kntu'
Less Than {<key>:{$lt:<value>}} db.mycol.find({"likes":{$lt:50}}).pretty() where likes < 50
Less Than
Equals
{<key>:{$lte:<value>}} db.mycol.find({"likes":{$lte:50}}).pretty() where likes <= 50
Greater Than {<key>:{$gt:<value>}} db.mycol.find({"likes":{$gt:50}}).pretty() where likes > 50
Greater Than
Equals
{<key>:{$gte:<value>}} db.mycol.find({"likes":{$gte:50}}).pretty() where likes >= 50
Not Equals {<key>:{$ne:<value>}} db.mycol.find({"likes":{$ne:50}}).pretty() where likes != 50
Values in an
array
{<key>:{$in:[<value1>,
<value2>,……<valueN>]
}}
db.mycol.find({"name":{$in:["Raj","Ram","Raghu"])
.pretty()
Where name matches any of the
value in :["Raj", "Ram", "Raghu"]
Values not in
array
{<key>:{$nin:<value>}} db.mycol.find({"name":{$nin:["Ramu","Raghav"]}})
.pretty()
Where name values is not in the
array :["Ramu", "Raghav"] or,
doesn’t exist at all
Query Document
 Example :
>db.mycol.find($and:{"likes": {$gt:10}, $or: [{"by": “kntu"},
{"title": "MongoDB Overview"}]}).pretty()
{
"_id": ObjectId(7df78ad8902c),
"title": "MongoDB Overview",
"description": "MongoDB is no sql database",
"by": “kntu",
"url": "http://kntu.ac.ir",
"tags": ["mongodb", "database", "NoSQL"],
"likes": "100“
}
Update Document
 MongoDB's update() and save() methods are used to update document into a
collection.
 update() Vs save()
 >db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)
 >db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})
 findOneAndUpdate()
 updateOne()
 updateMany(<filter>, <update>)
Delete Document
 MongoDB's remove() method accepts two parameters. One is deletion criteria
and second is justOne flag.
 deletion criteria − (Optional) deletion criteria according to documents will be
removed.
 justOne − (Optional) if set to true or 1, then remove only one document.
Relationships
 Embedded approach.
 Referenced approach.
Projection
 In MongoDB, projection means selecting only the necessary data rather than
selecting whole of the data of a document.
 The find() Method
 >db.COLLECTION_NAME.find({},{KEY:1})
Example :
{_id : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"},
{_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"},
{_id : ObjectId("507f191e810c19729de860e3"), title: “Redis Overview"}
>db.mycol.find({},{"title":1,_id:0})
{"title":"MongoDB Overview"} {"title":"NoSQL Overview"} {"title":“Redis Overview"}
_id field is always displayed while executing find() method, if you don't want this field, then you
need to set it as 0.
Limiting Records
 To limit the records in MongoDB we use two method :
 The Limit() Method
 Skip() Method
 These methods accepts one number type argument, which is the number of
documents that you want to be displayed or passed.
Example :
{_id : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"},
{_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"},
{_id : ObjectId("507f191e810c19729de860e3"), title: “Redis Overview"}
>db.mycol.find({},{"title":1,_id:0}).limit(1).skip(1)
{"title":"NoSQL Overview"}
Sorting Records
 The method accepts a document containing a list of fields along with their
sorting order. To specify sorting order 1 and -1 are used. 1 is used for
ascending order while -1 is used for descending order.
 The sort() Method
 >db.COLLECTION_NAME.find().sort({KEY:1})
Indexing
 Indexes support the efficient resolution of queries. Without indexes, MongoDB
must scan every document of a collection to select those documents that
match the query statement.
 The createIndex() Method >db.COLLECTION_NAME.createIndex({KEY:1/-1})
The method has some other parameters and I passed.
 The dropIndex() method >db.COLLECTION_NAME.dropIndex({KEY:1})
 The getIndexes() method : returns the description of all the indexes in the
collection.
Aggregation
 Aggregations operations process data records and return computed results.
 In SQL count(*) and with group by is an equivalent of MongoDB aggregation.
 aggregate() Method
 >db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
 $sum,$avg,$min,$max,$first,$last
 $push : Inserts the value to an array in the resulting document.
 $addToSet : Inserts the value to an array in the resulting
document but does not create duplicates.
Aggregation
Following are the possible stages in aggregation framework
 $project − Used to select some specific fields from a collection.
 $match − This is a filtering operation and thus this can reduce the amount
of documents that are given as input to the next stage.
 $group − This does the actual aggregation as discussed above.
 $sort − Sorts the documents.
 $skip − With this, it is possible to skip forward in the list of documents for
a given amount of documents.
 $limit − This limits the amount of documents to look at, by the given
number starting from the current positions.
 $unwind − This is used to unwind document that are using arrays. When
using an array, the data is kind of pre-joined and this operation will be
undone with this to have individual documents again. Thus with this stage
we will increase the amount of documents for the next stage.
Replication
 is the process of synchronizing data across multiple servers.
 provides redundancy and increases data availability with multiple copies of data
on different database servers.
 protects a database from the loss of a single server.
 allows you to recover from hardware failure and service interruptions.
 MongoDB achieves replication by the use of replica set. A replica set is a group
of mongod instances that host the same data set.
 Replica Set Features
 A cluster of N nodes
 Any one node can be primary
 All write operations go to primary
 Automatic failover--a method of protecting computer system
 Automatic recovery
 Consensus election of primary
Sharding
 is the process of storing data records across multiple machines and it is
MongoDB's approach to meeting the demands of data growth.
 solves the problem with horizontal scaling.
 Why Sharding?
 In replication, all writes go to master node
 Latency sensitive queries still go to master
 Single replica set has limitation of 12 nodes
 Memory can't be large enough when active dataset is big
 Local disk is not big enough
 Vertical scaling is too expensive
Sharding in MongoDB
 Shards − Shards are used to store data.
 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.
 Query Routers − Query routers are basically mongo instances,
interface with client applications and direct operations to the
appropriate shard.
Who is using MongoDB?

More Related Content

What's hot

An introduction to Nosql
An introduction to NosqlAn introduction to Nosql
An introduction to Nosql
greprep
 
Object oriented databases
Object oriented databasesObject oriented databases
Object oriented databases
Sajith Ekanayaka
 
XFILES, The APEX 4 version - The truth is in there
XFILES, The APEX 4 version - The truth is in thereXFILES, The APEX 4 version - The truth is in there
XFILES, The APEX 4 version - The truth is in there
Marco Gralike
 
BGOUG 2012 - Design concepts for xml applications that will perform
BGOUG 2012 - Design concepts for xml applications that will performBGOUG 2012 - Design concepts for xml applications that will perform
BGOUG 2012 - Design concepts for xml applications that will perform
Marco Gralike
 
BGOUG 2012 - Drag & drop and other stuff - Using your database as a file server
BGOUG 2012 - Drag & drop and other stuff - Using your database as a file serverBGOUG 2012 - Drag & drop and other stuff - Using your database as a file server
BGOUG 2012 - Drag & drop and other stuff - Using your database as a file server
Marco Gralike
 
Mongodb
MongodbMongodb
Understanding XML DOM
Understanding XML DOMUnderstanding XML DOM
Understanding XML DOM
Om Vikram Thapa
 
UKOUG 2011 - Drag, Drop and other Stuff. Using your Database as a File Server
UKOUG 2011 - Drag, Drop and other Stuff. Using your Database as a File ServerUKOUG 2011 - Drag, Drop and other Stuff. Using your Database as a File Server
UKOUG 2011 - Drag, Drop and other Stuff. Using your Database as a File ServerMarco Gralike
 
NHibernate
NHibernateNHibernate
NHibernate
gabrielcerutti
 
Difference between xml and json
Difference between xml and jsonDifference between xml and json
Difference between xml and json
Umar Ali
 
Mongo DB Presentation
Mongo DB PresentationMongo DB Presentation
Mongo DB Presentation
Jaya Naresh Kovela
 
Ontology-based Cooperation of Information Systems
Ontology-based Cooperation of Information SystemsOntology-based Cooperation of Information Systems
Ontology-based Cooperation of Information Systems
Raji Ghawi
 
Introduction To NHibernate
Introduction To NHibernateIntroduction To NHibernate
Introduction To NHibernate
Emad Alashi
 
OPP2010 (Brussels) - Programming with XML in PL/SQL - Part 1
OPP2010 (Brussels) - Programming with XML in PL/SQL - Part 1OPP2010 (Brussels) - Programming with XML in PL/SQL - Part 1
OPP2010 (Brussels) - Programming with XML in PL/SQL - Part 1Marco Gralike
 
Xml dom
Xml domXml dom
Xml dom
sana mateen
 
XML Amsterdam - Creating structure in unstructured data
XML Amsterdam - Creating structure in unstructured dataXML Amsterdam - Creating structure in unstructured data
XML Amsterdam - Creating structure in unstructured data
Marco Gralike
 
Introduction to NHibernate
Introduction to NHibernateIntroduction to NHibernate
Introduction to NHibernateDublin Alt,Net
 
NHibernate (The ORM For .NET Platform)
NHibernate (The ORM For .NET Platform)NHibernate (The ORM For .NET Platform)
NHibernate (The ORM For .NET Platform)Samnang Chhun
 
NHibernate for .NET
NHibernate for .NETNHibernate for .NET
NHibernate for .NETGuo Albert
 

What's hot (20)

An introduction to Nosql
An introduction to NosqlAn introduction to Nosql
An introduction to Nosql
 
Object oriented databases
Object oriented databasesObject oriented databases
Object oriented databases
 
XFILES, The APEX 4 version - The truth is in there
XFILES, The APEX 4 version - The truth is in thereXFILES, The APEX 4 version - The truth is in there
XFILES, The APEX 4 version - The truth is in there
 
BGOUG 2012 - Design concepts for xml applications that will perform
BGOUG 2012 - Design concepts for xml applications that will performBGOUG 2012 - Design concepts for xml applications that will perform
BGOUG 2012 - Design concepts for xml applications that will perform
 
BGOUG 2012 - Drag & drop and other stuff - Using your database as a file server
BGOUG 2012 - Drag & drop and other stuff - Using your database as a file serverBGOUG 2012 - Drag & drop and other stuff - Using your database as a file server
BGOUG 2012 - Drag & drop and other stuff - Using your database as a file server
 
Mongodb
MongodbMongodb
Mongodb
 
Understanding XML DOM
Understanding XML DOMUnderstanding XML DOM
Understanding XML DOM
 
UKOUG 2011 - Drag, Drop and other Stuff. Using your Database as a File Server
UKOUG 2011 - Drag, Drop and other Stuff. Using your Database as a File ServerUKOUG 2011 - Drag, Drop and other Stuff. Using your Database as a File Server
UKOUG 2011 - Drag, Drop and other Stuff. Using your Database as a File Server
 
NHibernate
NHibernateNHibernate
NHibernate
 
Difference between xml and json
Difference between xml and jsonDifference between xml and json
Difference between xml and json
 
Mongo DB Presentation
Mongo DB PresentationMongo DB Presentation
Mongo DB Presentation
 
Ontology-based Cooperation of Information Systems
Ontology-based Cooperation of Information SystemsOntology-based Cooperation of Information Systems
Ontology-based Cooperation of Information Systems
 
Introduction To NHibernate
Introduction To NHibernateIntroduction To NHibernate
Introduction To NHibernate
 
OPP2010 (Brussels) - Programming with XML in PL/SQL - Part 1
OPP2010 (Brussels) - Programming with XML in PL/SQL - Part 1OPP2010 (Brussels) - Programming with XML in PL/SQL - Part 1
OPP2010 (Brussels) - Programming with XML in PL/SQL - Part 1
 
Xml dom
Xml domXml dom
Xml dom
 
XML Amsterdam - Creating structure in unstructured data
XML Amsterdam - Creating structure in unstructured dataXML Amsterdam - Creating structure in unstructured data
XML Amsterdam - Creating structure in unstructured data
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
Introduction to NHibernate
Introduction to NHibernateIntroduction to NHibernate
Introduction to NHibernate
 
NHibernate (The ORM For .NET Platform)
NHibernate (The ORM For .NET Platform)NHibernate (The ORM For .NET Platform)
NHibernate (The ORM For .NET Platform)
 
NHibernate for .NET
NHibernate for .NETNHibernate for .NET
NHibernate for .NET
 

Similar to Introduction to MongoDB

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
 
Mongo db Quick Guide
Mongo db Quick GuideMongo db Quick Guide
Mongo db Quick Guide
Sourabh Sahu
 
Mongodb Introduction
Mongodb IntroductionMongodb Introduction
Mongodb Introduction
Raghvendra Parashar
 
Mongo db
Mongo dbMongo db
Mongo db
Gyanendra Yadav
 
NOSQL and MongoDB Database
NOSQL and MongoDB DatabaseNOSQL and MongoDB Database
NOSQL and MongoDB Database
Tariqul islam
 
MongoDB
MongoDBMongoDB
MongoDB
kesavan N B
 
Storage dei dati con MongoDB
Storage dei dati con MongoDBStorage dei dati con MongoDB
Storage dei dati con MongoDB
Andrea Balducci
 
Introduction to MongoDB and Workshop
Introduction to MongoDB and WorkshopIntroduction to MongoDB and Workshop
Introduction to MongoDB and Workshop
AhmedabadJavaMeetup
 
Mongo DB
Mongo DBMongo DB
MongoDB
MongoDBMongoDB
MongoDB
wiTTyMinds1
 
MongoDB - An Introduction
MongoDB - An IntroductionMongoDB - An Introduction
MongoDB - An Introduction
sethfloydjr
 
Query Optimization in MongoDB
Query Optimization in MongoDBQuery Optimization in MongoDB
Query Optimization in MongoDB
Hamoon Mohammadian Pour
 
Mongodb By Vipin
Mongodb By VipinMongodb By Vipin
Mongodb By Vipin
Vipin Mundayad
 
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 learning series
Mongo learning series Mongo learning series
Mongo learning series
Prashanth Panduranga
 
fard car.pptx
fard car.pptxfard car.pptx
fard car.pptx
tarungupta276841
 
MongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB .local London 2019: Fast Machine Learning Development with MongoDBMongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB
 
MongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB .local London 2019: Fast Machine Learning Development with MongoDBMongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB .local London 2019: Fast Machine Learning Development with MongoDB
Lisa Roth, PMP
 

Similar to Introduction to MongoDB (20)

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
 
Mongo db Quick Guide
Mongo db Quick GuideMongo db Quick Guide
Mongo db Quick Guide
 
Mongodb Introduction
Mongodb IntroductionMongodb Introduction
Mongodb Introduction
 
Mongo db
Mongo dbMongo db
Mongo db
 
NOSQL and MongoDB Database
NOSQL and MongoDB DatabaseNOSQL and MongoDB Database
NOSQL and MongoDB Database
 
MongoDB
MongoDBMongoDB
MongoDB
 
Storage dei dati con MongoDB
Storage dei dati con MongoDBStorage dei dati con MongoDB
Storage dei dati con MongoDB
 
lecture_34e.pptx
lecture_34e.pptxlecture_34e.pptx
lecture_34e.pptx
 
Introduction to MongoDB and Workshop
Introduction to MongoDB and WorkshopIntroduction to MongoDB and Workshop
Introduction to MongoDB and Workshop
 
Mongo DB
Mongo DBMongo DB
Mongo DB
 
MongoDB
MongoDBMongoDB
MongoDB
 
MongoDB - An Introduction
MongoDB - An IntroductionMongoDB - An Introduction
MongoDB - An Introduction
 
Query Optimization in MongoDB
Query Optimization in MongoDBQuery Optimization in MongoDB
Query Optimization in MongoDB
 
Mongodb By Vipin
Mongodb By VipinMongodb By Vipin
Mongodb By Vipin
 
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 learning series
Mongo learning series Mongo learning series
Mongo learning series
 
fard car.pptx
fard car.pptxfard car.pptx
fard car.pptx
 
MongoDB
MongoDBMongoDB
MongoDB
 
MongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB .local London 2019: Fast Machine Learning Development with MongoDBMongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB .local London 2019: Fast Machine Learning Development with MongoDB
 
MongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB .local London 2019: Fast Machine Learning Development with MongoDBMongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB .local London 2019: Fast Machine Learning Development with MongoDB
 

More from S.Shayan Daneshvar

Image to image translation with Pix2Pix GAN
Image to image translation with Pix2Pix GANImage to image translation with Pix2Pix GAN
Image to image translation with Pix2Pix GAN
S.Shayan Daneshvar
 
Microservice architecture (MSA) and patterns
Microservice architecture (MSA) and patternsMicroservice architecture (MSA) and patterns
Microservice architecture (MSA) and patterns
S.Shayan Daneshvar
 
P, NP and NP-Complete, Theory of NP-Completeness V2
P, NP and NP-Complete, Theory of NP-Completeness V2P, NP and NP-Complete, Theory of NP-Completeness V2
P, NP and NP-Complete, Theory of NP-Completeness V2
S.Shayan Daneshvar
 
Longest increasing subsequence
Longest increasing subsequenceLongest increasing subsequence
Longest increasing subsequence
S.Shayan Daneshvar
 
Analysis of algorithms
Analysis of algorithmsAnalysis of algorithms
Analysis of algorithms
S.Shayan Daneshvar
 
Amortized analysis
Amortized analysisAmortized analysis
Amortized analysis
S.Shayan Daneshvar
 

More from S.Shayan Daneshvar (6)

Image to image translation with Pix2Pix GAN
Image to image translation with Pix2Pix GANImage to image translation with Pix2Pix GAN
Image to image translation with Pix2Pix GAN
 
Microservice architecture (MSA) and patterns
Microservice architecture (MSA) and patternsMicroservice architecture (MSA) and patterns
Microservice architecture (MSA) and patterns
 
P, NP and NP-Complete, Theory of NP-Completeness V2
P, NP and NP-Complete, Theory of NP-Completeness V2P, NP and NP-Complete, Theory of NP-Completeness V2
P, NP and NP-Complete, Theory of NP-Completeness V2
 
Longest increasing subsequence
Longest increasing subsequenceLongest increasing subsequence
Longest increasing subsequence
 
Analysis of algorithms
Analysis of algorithmsAnalysis of algorithms
Analysis of algorithms
 
Amortized analysis
Amortized analysisAmortized analysis
Amortized analysis
 

Recently uploaded

Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
NaapbooksPrivateLimi
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
KrzysztofKkol1
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
varshanayak241
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
ayushiqss
 

Recently uploaded (20)

Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
 

Introduction to MongoDB

  • 2. Outline  Introduction  Overview of MongoDB’s Documents, Collections and Databases  Comparison of RDBMS and MongoDB  More on ObjectID  MongoDB Datatypes  Document Sample  MongoDB Advantages and where to use it  Create and Drop for Collections, Documents and Databases  CRUD Operations for Documents  Relations in MongoDB  Projection  Limiting, Sorting and Indexing in MongoDB  Replication and Sharding in Mongo DB  Companies that use MongoDB
  • 3. MongoDB is an open-source document database and leading NoSQL database. MongoDB is written mostly in C++. Released in 2009 Initial Release Document Based Types of NoSQL Databases: • Document-Based • Key-value stores • Wide Column • Graph NoSQL Humongous Scalable & Reliable Cross-Platform Available on Different Platforms
  • 4. Overview  Database 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 Collection is a group of MongoDB documents. It is the equivalent of an RDBMS table. A collection exists within a single database. 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.  Document 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.
  • 5. RDBMS vs 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. Advantages  Schema less − MongoDB is a document database in which one collection holds different documents. Number of fields, content and size of the document can differ from one document to another.  Structure of a single object is clear.  No complex joins.  Deep query-ability. MongoDB supports dynamic queries on documents using a document-based query language that's nearly as powerful as SQL.  Tuning.  Ease of scale-out − MongoDB is easy to scale.  Uses internal memory for storing the (windowed) working set, enabling faster access of data.
  • 7. Why MongoDB?  Document Oriented Storage − Data is stored in the form of JSON style documents.  Index on any attribute  Replication and high availability  Auto-Sharding  Rich queries  Fast in-place updates
  • 8. Where to Use MongoDB?  Big Data  Content Management and Delivery  Mobile and Social Infrastructure  User Data Management  Data Hub
  • 9. Sample Document { "_id" : ObjectId("5ecb9ea70403c0aa6001b4a2"), "brand" : "BMW", "model" : "X5", "tier" : "B", "max_speed" : 220, "color" : "Black", "airbags" : [ "front-seats", "back-seats", "other places" ] } _id is 12 bytes hexadecimal number unique for every document in a collection. You can provide it yourself too!
  • 10. ObjectID  An ObjectId is a 12-byte BSON type having the following structure  Generate By mongoDB >newObjectId = ObjectId()  ObjectId("5349b4ddd2781d08c09890f3")  Generate By us >myObjectId = ObjectId("5349b4ddd2781d08c09890f4")
  • 11. Datatypes  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.  Boolean − This type is used to store a boolean (true/ false) value.  Double − This type is used to store floating point values.  Min/ Max keys − This type is used to compare a value against the lowest and highest BSON elements.  Arrays − This type is used to store arrays or list or multiple values into one key.  Timestamp − ctimestamp. This can be handy for recording when a document has been modified or added.  Object − This datatype is used for embedded documents.  Null − This type is used to store a Null value.  Symbol − This datatype is used identically to a string; however, it's generally reserved for languages that use a specific symbol type.  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.  Object ID − This datatype is used to store the document’s ID.  Binary data − This datatype is used to store binary data.  Code − This datatype is used to store JavaScript code into the document.  Regular expression − This datatype is used to store regular expression.
  • 12. Create & Drop Database  MongoDB use DATABASE_NAME is used to create database. The command will create a new database if it doesn't exist, otherwise it will return the existing database.  MongoDB db.dropDatabase() command is used to drop a existing database. Example: use divarDB db.dropDatabase()  If you want to check your databases list, use the command show dbs.
  • 13. Create Collections  MongoDB db.createCollection(name, options) is used to create collection. db.createCollection("mycol", { capped : true, autoIndexID : true, size : 6142800, max : 10000 } ) Parameter Type Name String Options Document Field Type Description capped Boolean If true, enables a capped collection. Capped collection is a fixed size collection that automatically overwrites its oldest entries when it reaches its maximum size. If you specify true, you need to specify size parameter also. autoIn dexId Boolean If true, automatically create index on _id fields. size number Specifies a maximum size in bytes for a capped collection. If capped is true, then you need to specify this field also. max number Specifies the maximum number of documents allowed in the capped collection.
  • 14. Drop Collections  MongoDB's db.collection.drop() is used to drop a collection from the database.  show collections is used to show all collections in the current Example: db.mycollection.drop()
  • 15. Insert Document  To insert data into MongoDB collection, you need to use MongoDB's insert() or save() method.  If you need to insert only one document you can use insertOne() method.  You can insert multiple documents using the insertMany() method. To this method you need to pass an array of documents. Example: db.stuff.insert({ title: "MongoDB Insert Docs", description: "MongoDB is no sql database", tags: ['mongodb', 'database', 'NoSQL'], likes: 100 }) db.presenters.insertMany([ { First_Name: “Shayan", Last_Name: “Daneshvar", }, { First_Name: “Hashem", Last_Name: “Pourallahverdi", }])
  • 16. Query Document how to query document from MongoDB collection.  The find() Method  The pretty() Method  The findOne() method  AND  OR  NOR  NOT Operation Syntax Example RDBM S Equivalent Equality {<key>:{$eg;<value>}} db.mycol.find({"by":"kntu"}).pretty() where by = 'kntu' Less Than {<key>:{$lt:<value>}} db.mycol.find({"likes":{$lt:50}}).pretty() where likes < 50 Less Than Equals {<key>:{$lte:<value>}} db.mycol.find({"likes":{$lte:50}}).pretty() where likes <= 50 Greater Than {<key>:{$gt:<value>}} db.mycol.find({"likes":{$gt:50}}).pretty() where likes > 50 Greater Than Equals {<key>:{$gte:<value>}} db.mycol.find({"likes":{$gte:50}}).pretty() where likes >= 50 Not Equals {<key>:{$ne:<value>}} db.mycol.find({"likes":{$ne:50}}).pretty() where likes != 50 Values in an array {<key>:{$in:[<value1>, <value2>,……<valueN>] }} db.mycol.find({"name":{$in:["Raj","Ram","Raghu"]) .pretty() Where name matches any of the value in :["Raj", "Ram", "Raghu"] Values not in array {<key>:{$nin:<value>}} db.mycol.find({"name":{$nin:["Ramu","Raghav"]}}) .pretty() Where name values is not in the array :["Ramu", "Raghav"] or, doesn’t exist at all
  • 17. Query Document  Example : >db.mycol.find($and:{"likes": {$gt:10}, $or: [{"by": “kntu"}, {"title": "MongoDB Overview"}]}).pretty() { "_id": ObjectId(7df78ad8902c), "title": "MongoDB Overview", "description": "MongoDB is no sql database", "by": “kntu", "url": "http://kntu.ac.ir", "tags": ["mongodb", "database", "NoSQL"], "likes": "100“ }
  • 18. Update Document  MongoDB's update() and save() methods are used to update document into a collection.  update() Vs save()  >db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)  >db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})  findOneAndUpdate()  updateOne()  updateMany(<filter>, <update>)
  • 19. Delete Document  MongoDB's remove() method accepts two parameters. One is deletion criteria and second is justOne flag.  deletion criteria − (Optional) deletion criteria according to documents will be removed.  justOne − (Optional) if set to true or 1, then remove only one document.
  • 21. Projection  In MongoDB, projection means selecting only the necessary data rather than selecting whole of the data of a document.  The find() Method  >db.COLLECTION_NAME.find({},{KEY:1}) Example : {_id : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"}, {_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"}, {_id : ObjectId("507f191e810c19729de860e3"), title: “Redis Overview"} >db.mycol.find({},{"title":1,_id:0}) {"title":"MongoDB Overview"} {"title":"NoSQL Overview"} {"title":“Redis Overview"} _id field is always displayed while executing find() method, if you don't want this field, then you need to set it as 0.
  • 22. Limiting Records  To limit the records in MongoDB we use two method :  The Limit() Method  Skip() Method  These methods accepts one number type argument, which is the number of documents that you want to be displayed or passed. Example : {_id : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"}, {_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"}, {_id : ObjectId("507f191e810c19729de860e3"), title: “Redis Overview"} >db.mycol.find({},{"title":1,_id:0}).limit(1).skip(1) {"title":"NoSQL Overview"}
  • 23. Sorting Records  The method accepts a document containing a list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.  The sort() Method  >db.COLLECTION_NAME.find().sort({KEY:1})
  • 24. Indexing  Indexes support the efficient resolution of queries. Without indexes, MongoDB must scan every document of a collection to select those documents that match the query statement.  The createIndex() Method >db.COLLECTION_NAME.createIndex({KEY:1/-1}) The method has some other parameters and I passed.  The dropIndex() method >db.COLLECTION_NAME.dropIndex({KEY:1})  The getIndexes() method : returns the description of all the indexes in the collection.
  • 25. Aggregation  Aggregations operations process data records and return computed results.  In SQL count(*) and with group by is an equivalent of MongoDB aggregation.  aggregate() Method  >db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)  $sum,$avg,$min,$max,$first,$last  $push : Inserts the value to an array in the resulting document.  $addToSet : Inserts the value to an array in the resulting document but does not create duplicates.
  • 26. Aggregation Following are the possible stages in aggregation framework  $project − Used to select some specific fields from a collection.  $match − This is a filtering operation and thus this can reduce the amount of documents that are given as input to the next stage.  $group − This does the actual aggregation as discussed above.  $sort − Sorts the documents.  $skip − With this, it is possible to skip forward in the list of documents for a given amount of documents.  $limit − This limits the amount of documents to look at, by the given number starting from the current positions.  $unwind − This is used to unwind document that are using arrays. When using an array, the data is kind of pre-joined and this operation will be undone with this to have individual documents again. Thus with this stage we will increase the amount of documents for the next stage.
  • 27. Replication  is the process of synchronizing data across multiple servers.  provides redundancy and increases data availability with multiple copies of data on different database servers.  protects a database from the loss of a single server.  allows you to recover from hardware failure and service interruptions.  MongoDB achieves replication by the use of replica set. A replica set is a group of mongod instances that host the same data set.  Replica Set Features  A cluster of N nodes  Any one node can be primary  All write operations go to primary  Automatic failover--a method of protecting computer system  Automatic recovery  Consensus election of primary
  • 28. Sharding  is the process of storing data records across multiple machines and it is MongoDB's approach to meeting the demands of data growth.  solves the problem with horizontal scaling.  Why Sharding?  In replication, all writes go to master node  Latency sensitive queries still go to master  Single replica set has limitation of 12 nodes  Memory can't be large enough when active dataset is big  Local disk is not big enough  Vertical scaling is too expensive
  • 29. Sharding in MongoDB  Shards − Shards are used to store data.  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.  Query Routers − Query routers are basically mongo instances, interface with client applications and direct operations to the appropriate shard.
  • 30. Who is using MongoDB?