MongoDB
Ram Murat Sharma | @rammrms | rammurat.rms.sharma0@gmail.com
Agenda
 Prerequisite
 Introduction to MongoDB
 MongoDB vs RDBMS Structure
 Basic CRUD Operations
 Create, Update, Delete & Drop
 Sort, Limit & Indexing
 Where Clause
 Aggregation()
 Connect with Node
 Sharding
 Replication
 Backup/Restore Data
 Access MongoDB with Server Side language (Node)
 Why MongoDB?
 Questions
Prerequisites
 What you should know already
 Basic knowledge of JavaScript
 Basic knowledge of Server Side language
 Good knowledge of JSON
 Good knowledge of Database
 Technical preparations
 Any browser running on your laptop/Desktop
 Any server side language running like PHP, Node etc.
 Your IDE or code editor of choice
 Any server running to respond query like Tomcat, Xampp or
Node
Introduction to MongoDB
MongoDB is a cross-platform, document oriented
database that provides, high performance, high
availability, and easy scalability.
Key Structure
 Database - Database is a physical container for collections. Each database
gets its own set of files on the file system.
 Collection - Collection is a group of MongoDB documents. It is the equivalent
of an RDBMS table. A collection exists within a single database. 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.
RDBMS MongoDB
Database Database
Table Collection
Row Document
Column Field
Join Embedded Documents
Primary Key _id (Provided by MongoDB)
Database Server and Client
MySqlD/Oracle mongoD
MySql/SqlPlus mongo
RDBMS VS MongoDB
Structure Example
SQL No SQL
Basic Commands
Operation Command
Create Database Use <dbname>
Switch Database Use <dbname>
List current Database Db
List all databases Show dbs
Drop Database Db.dropDatabase()
Create Collection db.createCollection(name, options)
db.createCollection(“Sapient”, {max:1000})
List collection Show collections
Drop Collection db.COLLECTION_NAME.drop()
Operation Command
Insert Document db.COLLECTION_NAME.insert(document)
db.employees.insert({
‘title’: ‘Associate L2',
‘oracle_id’: 104495,
‘education’: [‘BCA', ‘MCA'],
‘projects’:{ ‘id’:232323,’Strengh’:60 }
})
Update Document db.COLLECTION_NAME.update(SELECTIOIN_C
RITERIA, UPDATED_DATA)
db.employees.update(
{ ‘oracle_id’: 104495},
{ $set: {‘title’: ‘Senior Associate L2’}}
)
Delete Document(s)
Delete one record from result set in case
multiple records
db.COLLECTION_NAME.remove(DELLETION_C
RITTERIA)
db.employees.remove({'title':‘Associate L2'})
db.employees.remove({'title':‘Associate L2'},1)
Operation Command
Empty Document db.COLLECTION_NAME.remove()
Find Document(s) db.COLLECTION_NAME.find()
db.employees.find()
db.employees.find().pretty()
db.employees.find(
{ ‘oracle_id’: 104495}
).pretty()
Find (Projection)
Limit the result set
db.COLLECTION_NAME.find({},{KEY:1})
Where Clause in MongoDB
Operation MongoDB RDBMS
Equality db.employees.find({“salary":“5000"}) where ‘salary ‘= ‘5000’
Less Than db.employees.find({“age":{$lt:30}}) where age < 30
Less Than
Equals
db.employees.find({“age":{$lte:30}}) where age <= 30
Greater Than db.employees.find({“age":{$gt:30}}) where age > 30
Greater Than
Equals
db.employees.find({“age":{$gte:30}}) where age >= 30
Not Equals db.employees.find({“age":{$ne:30}}) where age != 30
Operation Command
Sorting
(1 Asc)
(-1 Desc)
db.COLLECTION_NAME.find().sort({KEY:1})
db.employees.find({"title":’Associate L2’}).sort({‘title’:1})
Limit records db.COLLECTION_NAME.find().limit(NUMBER)
db.employees.find({"title":’Associate L2’}).limit(2)
Skip records db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
db.employees.find({"title":’Associate L2’}).skip(1)
Indexing db.COLLECTION_NAME.ensureIndex({KEY:1})
db.employees.ensureIndex({"title":1})
Aggregation()
Aggregations operations process data records and return computed
results. Aggregation operations group values from multiple
documents together, and can perform a variety of operations on the
grouped data to return a single result. In sql, count(*) and “group
by” is an equivalent of mongodb aggregation.
 Syntax - db.employees.aggregate([{$group : {_id :
"$oracle_id", title : {$sum : 1}}}])
 Options - $avg, $min, $max, $push , $first & $last
Connect with NODE
MongoDB Dump/Restore
To create backup of database in mongodb you should
use mongodump command. This command will dump all data of
your server into dump directory. There are many options available
by which you can limit the amount of data or create backup of your
remote server.
 Steps:
 Make sure mongo server is running
 Go to bin Mongo bin/ directory
 Type mongodump/mongorestore
 Look for bin/dump/ folder, it contains dump data now
Sharding
Sharding is the process of storing data records across multiple
macines and it is MongoDB’s approach to meeting the demands of
data growth.
Problem – As the size of the data increases, a single machine may
not be sufficient to store the data nor provide an acceptable read
and write throughput.
Solution – Sharding this problem with horizontal scaling where you
can add more machines to support data growth and the demands of
read and write operations.
Why Replication?
Replication is the process of synchronizing data across multiple servers.
Replication provides redundancy and increases data availability with
multiple copies of data on different database servers, replication protects
a database from the loss of a single server. Replication also allows you to
recover from hardware failure and service interruptions. With additional
copies of the data, you can dedicate one to disaster recovery, reporting, or
backup.
• To keep your data safe
• High availability of data (24*7)
• Disaster Recovery
• No downtime for maintenance (like backups, index rebuilds,
compaction)
• Read scaling (extra copies to read from)
Replication
Why MongoDB?
 Document Database
 Documents (objects) map nicely to programming language data types.
 Embedded documents and arrays reduce need for joins.
 Dynamic schema
 High Performance
 Embedding makes reads and writes fast.
 Indexes can include keys from embedded documents and arrays.
 High Availability
 Replicated servers with automatic master failover.
 Easy Scalability
 Automatic sharding distributes collection data across machines.
 Consistent reads can be distributed over replicated servers.
 Brands prefers Mongo - FourSquare, Adobe, McAfee, Ebay, Fifa, MetLife, Forbes and
more…
Questions?
&
Feedbacks
Thank You

MongoDB - A next-generation database that lets you create applications never before possible.

  • 1.
    MongoDB Ram Murat Sharma| @rammrms | rammurat.rms.sharma0@gmail.com
  • 2.
    Agenda  Prerequisite  Introductionto MongoDB  MongoDB vs RDBMS Structure  Basic CRUD Operations  Create, Update, Delete & Drop  Sort, Limit & Indexing  Where Clause  Aggregation()  Connect with Node  Sharding  Replication  Backup/Restore Data  Access MongoDB with Server Side language (Node)  Why MongoDB?  Questions
  • 3.
    Prerequisites  What youshould know already  Basic knowledge of JavaScript  Basic knowledge of Server Side language  Good knowledge of JSON  Good knowledge of Database  Technical preparations  Any browser running on your laptop/Desktop  Any server side language running like PHP, Node etc.  Your IDE or code editor of choice  Any server running to respond query like Tomcat, Xampp or Node
  • 4.
    Introduction to MongoDB MongoDBis a cross-platform, document oriented database that provides, high performance, high availability, and easy scalability. Key Structure  Database - Database is a physical container for collections. Each database gets its own set of files on the file system.  Collection - Collection is a group of MongoDB documents. It is the equivalent of an RDBMS table. A collection exists within a single database. 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.
  • 5.
    RDBMS MongoDB Database Database TableCollection Row Document Column Field Join Embedded Documents Primary Key _id (Provided by MongoDB) Database Server and Client MySqlD/Oracle mongoD MySql/SqlPlus mongo RDBMS VS MongoDB
  • 6.
  • 7.
    Basic Commands Operation Command CreateDatabase Use <dbname> Switch Database Use <dbname> List current Database Db List all databases Show dbs Drop Database Db.dropDatabase() Create Collection db.createCollection(name, options) db.createCollection(“Sapient”, {max:1000}) List collection Show collections Drop Collection db.COLLECTION_NAME.drop()
  • 8.
    Operation Command Insert Documentdb.COLLECTION_NAME.insert(document) db.employees.insert({ ‘title’: ‘Associate L2', ‘oracle_id’: 104495, ‘education’: [‘BCA', ‘MCA'], ‘projects’:{ ‘id’:232323,’Strengh’:60 } }) Update Document db.COLLECTION_NAME.update(SELECTIOIN_C RITERIA, UPDATED_DATA) db.employees.update( { ‘oracle_id’: 104495}, { $set: {‘title’: ‘Senior Associate L2’}} ) Delete Document(s) Delete one record from result set in case multiple records db.COLLECTION_NAME.remove(DELLETION_C RITTERIA) db.employees.remove({'title':‘Associate L2'}) db.employees.remove({'title':‘Associate L2'},1)
  • 9.
    Operation Command Empty Documentdb.COLLECTION_NAME.remove() Find Document(s) db.COLLECTION_NAME.find() db.employees.find() db.employees.find().pretty() db.employees.find( { ‘oracle_id’: 104495} ).pretty() Find (Projection) Limit the result set db.COLLECTION_NAME.find({},{KEY:1})
  • 10.
    Where Clause inMongoDB Operation MongoDB RDBMS Equality db.employees.find({“salary":“5000"}) where ‘salary ‘= ‘5000’ Less Than db.employees.find({“age":{$lt:30}}) where age < 30 Less Than Equals db.employees.find({“age":{$lte:30}}) where age <= 30 Greater Than db.employees.find({“age":{$gt:30}}) where age > 30 Greater Than Equals db.employees.find({“age":{$gte:30}}) where age >= 30 Not Equals db.employees.find({“age":{$ne:30}}) where age != 30
  • 11.
    Operation Command Sorting (1 Asc) (-1Desc) db.COLLECTION_NAME.find().sort({KEY:1}) db.employees.find({"title":’Associate L2’}).sort({‘title’:1}) Limit records db.COLLECTION_NAME.find().limit(NUMBER) db.employees.find({"title":’Associate L2’}).limit(2) Skip records db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER) db.employees.find({"title":’Associate L2’}).skip(1) Indexing db.COLLECTION_NAME.ensureIndex({KEY:1}) db.employees.ensureIndex({"title":1})
  • 12.
    Aggregation() Aggregations operations processdata records and return computed results. Aggregation operations group values from multiple documents together, and can perform a variety of operations on the grouped data to return a single result. In sql, count(*) and “group by” is an equivalent of mongodb aggregation.  Syntax - db.employees.aggregate([{$group : {_id : "$oracle_id", title : {$sum : 1}}}])  Options - $avg, $min, $max, $push , $first & $last
  • 14.
  • 15.
    MongoDB Dump/Restore To createbackup of database in mongodb you should use mongodump command. This command will dump all data of your server into dump directory. There are many options available by which you can limit the amount of data or create backup of your remote server.  Steps:  Make sure mongo server is running  Go to bin Mongo bin/ directory  Type mongodump/mongorestore  Look for bin/dump/ folder, it contains dump data now
  • 16.
    Sharding Sharding is theprocess of storing data records across multiple macines and it is MongoDB’s approach to meeting the demands of data growth. Problem – As the size of the data increases, a single machine may not be sufficient to store the data nor provide an acceptable read and write throughput. Solution – Sharding this problem with horizontal scaling where you can add more machines to support data growth and the demands of read and write operations.
  • 17.
    Why Replication? Replication isthe process of synchronizing data across multiple servers. Replication provides redundancy and increases data availability with multiple copies of data on different database servers, replication protects a database from the loss of a single server. Replication also allows you to recover from hardware failure and service interruptions. With additional copies of the data, you can dedicate one to disaster recovery, reporting, or backup. • To keep your data safe • High availability of data (24*7) • Disaster Recovery • No downtime for maintenance (like backups, index rebuilds, compaction) • Read scaling (extra copies to read from) Replication
  • 18.
    Why MongoDB?  DocumentDatabase  Documents (objects) map nicely to programming language data types.  Embedded documents and arrays reduce need for joins.  Dynamic schema  High Performance  Embedding makes reads and writes fast.  Indexes can include keys from embedded documents and arrays.  High Availability  Replicated servers with automatic master failover.  Easy Scalability  Automatic sharding distributes collection data across machines.  Consistent reads can be distributed over replicated servers.  Brands prefers Mongo - FourSquare, Adobe, McAfee, Ebay, Fifa, MetLife, Forbes and more…
  • 19.
  • 20.