SlideShare a Scribd company logo
Chris Kitechriskite.comIntro to MongoDB
In This Talk…What is MongoDB?Why use it?Documents and CollectionsQueryingJavaScript ShellSchema Design
What is MongoDB?
Not a RDBMSMongo is not a relational database like MySQLNo transactionsNo referential integrityNo joinsNo schema, so no columns or rowsNoSQL
Not a Key-Value StoreMongo is not simply a key-value store like RedisStores structured dataRich query interfaceIndexesMap/ReduceAutomatic sharding, GridFS, geospatial indexing, etc.
Document-oriented DatabaseRecords are JSON documents (actually BSON)Stored in collectionsNo predefined schemaDocs in the same collection don’t even need to have the same fieldsAtomic in-place operators for contention-free updates$set, $inc, $push, $pop, etc.
Mongo Documentuser = {	 name: "Frank Furter",	 occupation: "A scientist",	 location: "Transylvania"  }
Why Use MongoDB?
It’s Stupid Fast!Anywhere from 2 to 10 times faster than MySQLDepends on which contrived benchmark you’re looking atHere’s one I just made up:
It’s Stupid Fast!About 50 times faster than CouchDBAccording to http://www.idiotsabound.com/did-i-mention-mongodb-is-fast-way-to-go-mongo2 important points:It’s pretty quickBenchmarks are worthless unless you do them on your actual workload
It’s Web Scale!Sharding built-in, automatic, and *Just Works™*Just Works™ guarantee applies only if you have a cluster of shard replica sets with config servers and routing servers and you define your own shard key(s) with appropriate uniformity and granularityAsynchronous replication for failover and redundancy
It’s Pretty PainlessSchemalessNo more configuring database columns with typesNo more defining and managing migrationsJust stick your data in there, it’s fineNoSQLORMs exist mostly because writing SQL sucksMongo’s query language is basically JSONThe Mongo driver for your favorite language is really nice and officially supportedHandy JavaScript shell for the CLI
It’s Pretty PainlessMySQL/* First go create the database, the table, the schema, etc. */mysql_connect("localhost", "username", "password") or die(mysql_error());mysql_select_db("test") or die(mysql_error());$sql = "INSERT INTO users (name, age) VALUES ('Janet', 23)";mysql_query($sql);$result = mysql_query("SELECT * FROM users WHERE age = 23");$row = mysql_fetch_assoc($result);echo "Oh, " . $row['name'] . "!"; // prints "Oh, Janet!"MongoDB$mongo = new Mongo(); // defaults to localhost with no auth$users = $mongo->test_db->users; // database and collection created implicitly$users->insert( array('name' => 'Brad', 'age' => 25) );$user = $users->findOne( array('age' => 25) );echo "Oh, " . $user->name . "!"; // prints "Oh, Brad!"
All the Cool Kids Are Doing Ithttp://www.mongodb.org/display/DOCS/Production+Deployments
Documents and Collections
Documents and CollectionsDocuments are the recordsLike objects in OOP, or rows in RDBMSCollections are groups of documentsUsually represent a top-level class in your appHeterogeneous setUnlike RDBMS tables, no predefined schemaNo foreign keys, so how do we reference other objects?Don't! Just embed the sub-item in the parent docOr, use a key for references and deal with the fact that you don't get integrity or joins
Embedded ObjectsDocuments can embed other documentsUsed to efficiently represent a relationFor example:{  name: 'Brad Majors', address:    {     street: 'Oak Terrace',     city: 'Denton'   }}
Querying
QueriesQueries are documentsQuery expression objects indicate a pattern to matchdb.users.find( {last_name: 'Smith'} )Several query objects for advanced queriesdb.users.find( {age: {$gte: 23} } )db.users.find( {age: {$in: [23,25]} } )
Querying Embedded ObjectsExact match an entire embedded objectdb.users.find( {address: {street: 'Oak Terrace', city: 'Denton'}} )Dot-notation for a partial matchdb.users.find( {"address.city": 'Denton'} )
JavaScript Shell
JS ShellComes with MongoDBLaunch it with 'mongo' on the command-lineTry a simplified version at http://www.mongodb.org/Great fit since Mongo docs are basically JSON
Live DemoIf the tech demo gods allow it
Schema Design
I thought you said no schema?There is no predefined schemaYour application creates an ad-hoc schema with the objects it createsThe schema is implicit in the queries your application runs
Schema DesignUse collections to represent the top-level classes of your applicationBut don't just make a collection for every object typeThese aren't like tables in an RDBMSLess normalization, more embedding
Obligatory Blog Post ExampleA blog post has an author, some text, and many commentsThe comments are unique per post, but one author has many postsHow would you design this in SQL?Let's look at how we might design it in Mongo
Bad Schema Design: ReferencesCollections for posts, authors, and commentsReferences by manually created IDpost = { id: 150, author: 100, text: 'This is a pretty awesome post.', comments: [100, 105, 112]}author = { id: 100, name: 'Michael Arrington' posts: [150]}comment = { id: 105, text: 'Whatever this sux.'}
Better Schema Design: EmbeddingCollection for postsEmbed comments, author namepost = { author: 'Michael Arrington', text: 'This is a pretty awesome post.', comments: [            'Whatever this post sux.',             'I agree, lame!'           ]}
BenefitsEmbedded objects brought back in the same query as parent objectOnly 1 trip to the DB server requiredObjects in the same collection are generally stored contiguously on diskSpatial locality = fasterIf the document model matches your domain well, it can be much easier to comprehend than nasty joins
IndexesMongo supports indexes to greatly improve query performanceNo need to create in advanceCreate idempotent indexes in your app with "ensure_index"
Schema Design LimitationsNo referential integrityHigh degree of denormalization means updating something in many places instead of oneLack of predefined schema is a double-edged swordHopefully you have a model in your appObjects within a collection can be completely inconsistent in their fields
Final Thoughts
Final ThoughtsMongoDB is fast no matter how you slice itIt achieves high performance by literally playing fast and loose with your dataThat's not necessarily a bad thing, just a tradeoffVery rapid development, open sourceDocument model is simple but powerfulAdvanced features like map/reduce, geospatial indexing etc. are very compellingSurprisingly great drivers for most languages
Questions?
Thanks!These slides are online:http://bit.ly/intro_to_mongo

More Related Content

PPT
Introduction to mongodb
neela madheswari
 
PDF
MongoDB Fundamentals
MongoDB
 
PDF
PostgreSQL Tutorial For Beginners | Edureka
Edureka!
 
PPTX
Introduction to Elasticsearch
Ismaeel Enjreny
 
PDF
Mvcc in postgreSQL 권건우
PgDay.Seoul
 
PPTX
MongoDB.pptx
Sigit52
 
PDF
Mastering PostgreSQL Administration
EDB
 
PDF
Postgresql database administration volume 1
Federico Campoli
 
Introduction to mongodb
neela madheswari
 
MongoDB Fundamentals
MongoDB
 
PostgreSQL Tutorial For Beginners | Edureka
Edureka!
 
Introduction to Elasticsearch
Ismaeel Enjreny
 
Mvcc in postgreSQL 권건우
PgDay.Seoul
 
MongoDB.pptx
Sigit52
 
Mastering PostgreSQL Administration
EDB
 
Postgresql database administration volume 1
Federico Campoli
 

What's hot (20)

PDF
MySQL InnoDB Cluster - New Features in 8.0 Releases - Best Practices
Kenny Gryp
 
PPTX
ELK Stack
Phuc Nguyen
 
PDF
Introduction to MongoDB
Mike Dirolf
 
PPTX
Mongo db intro.pptx
JWORKS powered by Ordina
 
KEY
PostgreSQL
Reuven Lerner
 
PDF
Oracle to Postgres Migration - part 1
PgTraining
 
PDF
[pgday.Seoul 2022] 서비스개편시 PostgreSQL 도입기 - 진소린 & 김태정
PgDay.Seoul
 
PDF
Introduction to elasticsearch
hypto
 
PDF
Postgresql tutorial
Ashoka Vanjare
 
PDF
What’s the Best PostgreSQL High Availability Framework? PAF vs. repmgr vs. Pa...
ScaleGrid.io
 
PDF
Intro to Telegraf
InfluxData
 
PDF
All About JSON and ClickHouse - Tips, Tricks and New Features-2022-07-26-FINA...
Altinity Ltd
 
PDF
ClickHouse Query Performance Tips and Tricks, by Robert Hodges, Altinity CEO
Altinity Ltd
 
PDF
One PDB to go, please!
Christian Gohmann
 
PPTX
PostgreSQL- An Introduction
Smita Prasad
 
PPTX
Log management with ELK
Geert Pante
 
PDF
Introduction to elasticsearch
pmanvi
 
PPTX
Maxscale 소개 1.1.1
NeoClova
 
PDF
Incremental View Maintenance with Coral, DBT, and Iceberg
Walaa Eldin Moustafa
 
PPTX
Elastic Stack Introduction
Vikram Shinde
 
MySQL InnoDB Cluster - New Features in 8.0 Releases - Best Practices
Kenny Gryp
 
ELK Stack
Phuc Nguyen
 
Introduction to MongoDB
Mike Dirolf
 
Mongo db intro.pptx
JWORKS powered by Ordina
 
PostgreSQL
Reuven Lerner
 
Oracle to Postgres Migration - part 1
PgTraining
 
[pgday.Seoul 2022] 서비스개편시 PostgreSQL 도입기 - 진소린 & 김태정
PgDay.Seoul
 
Introduction to elasticsearch
hypto
 
Postgresql tutorial
Ashoka Vanjare
 
What’s the Best PostgreSQL High Availability Framework? PAF vs. repmgr vs. Pa...
ScaleGrid.io
 
Intro to Telegraf
InfluxData
 
All About JSON and ClickHouse - Tips, Tricks and New Features-2022-07-26-FINA...
Altinity Ltd
 
ClickHouse Query Performance Tips and Tricks, by Robert Hodges, Altinity CEO
Altinity Ltd
 
One PDB to go, please!
Christian Gohmann
 
PostgreSQL- An Introduction
Smita Prasad
 
Log management with ELK
Geert Pante
 
Introduction to elasticsearch
pmanvi
 
Maxscale 소개 1.1.1
NeoClova
 
Incremental View Maintenance with Coral, DBT, and Iceberg
Walaa Eldin Moustafa
 
Elastic Stack Introduction
Vikram Shinde
 
Ad

Viewers also liked (7)

PDF
Business considerations for node.js applications
Aspenware
 
KEY
Getting Started with MongoDB and Node.js
Grant Goodale
 
PPTX
Mongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorials
SpringPeople
 
PPTX
MongoDB-Beginner tutorial explaining basic operation via mongo shell
Priti Solanki
 
PDF
Intro To MongoDB
Alex Sharp
 
PPT
Introduction to MongoDB
Ravi Teja
 
Business considerations for node.js applications
Aspenware
 
Getting Started with MongoDB and Node.js
Grant Goodale
 
Mongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorials
SpringPeople
 
MongoDB-Beginner tutorial explaining basic operation via mongo shell
Priti Solanki
 
Intro To MongoDB
Alex Sharp
 
Introduction to MongoDB
Ravi Teja
 
Ad

Similar to Intro To Mongo Db (20)

PPT
Tech Gupshup Meetup On MongoDB - 24/06/2016
Mukesh Tilokani
 
PPTX
Introduction to MongoDB and Workshop
AhmedabadJavaMeetup
 
ODP
DrupalCon Chicago Practical MongoDB and Drupal
Doug Green
 
KEY
MongoDB
Steven Francia
 
PPTX
Jumpstart: Building Your First MongoDB App
MongoDB
 
PDF
Building your first app with MongoDB
Norberto Leite
 
PPTX
Mongo db
Gyanendra Yadav
 
PDF
Compass Framework
Lukas Vlcek
 
PPT
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
Rick Copeland
 
PPTX
Introduction to MongoDB
S.Shayan Daneshvar
 
PPT
Allura - an Open Source MongoDB Based Document Oriented SourceForge
Rick Copeland
 
ODP
This upload requires better support for ODP format
Forest Mars
 
PDF
Introduction to MongoDB
Justin Smestad
 
PPTX
MongoDB.local Sydney: An Introduction to Document Databases with MongoDB
MongoDB
 
PPTX
lecture_34e.pptx
janibashashaik25
 
PDF
Mongo learning series
Prashanth Panduranga
 
PPT
Architecture | Busy Java Developers Guide to NoSQL | Ted Neward
JAX London
 
PPT
Rapid, Scalable Web Development with MongoDB, Ming, and Python
Rick Copeland
 
PDF
The emerging world of mongo db csp
Carlos Sánchez Pérez
 
PDF
Use Performance Insights To Enhance MongoDB Performance - (Manosh Malai - Myd...
Mydbops
 
Tech Gupshup Meetup On MongoDB - 24/06/2016
Mukesh Tilokani
 
Introduction to MongoDB and Workshop
AhmedabadJavaMeetup
 
DrupalCon Chicago Practical MongoDB and Drupal
Doug Green
 
Jumpstart: Building Your First MongoDB App
MongoDB
 
Building your first app with MongoDB
Norberto Leite
 
Mongo db
Gyanendra Yadav
 
Compass Framework
Lukas Vlcek
 
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
Rick Copeland
 
Introduction to MongoDB
S.Shayan Daneshvar
 
Allura - an Open Source MongoDB Based Document Oriented SourceForge
Rick Copeland
 
This upload requires better support for ODP format
Forest Mars
 
Introduction to MongoDB
Justin Smestad
 
MongoDB.local Sydney: An Introduction to Document Databases with MongoDB
MongoDB
 
lecture_34e.pptx
janibashashaik25
 
Mongo learning series
Prashanth Panduranga
 
Architecture | Busy Java Developers Guide to NoSQL | Ted Neward
JAX London
 
Rapid, Scalable Web Development with MongoDB, Ming, and Python
Rick Copeland
 
The emerging world of mongo db csp
Carlos Sánchez Pérez
 
Use Performance Insights To Enhance MongoDB Performance - (Manosh Malai - Myd...
Mydbops
 

Recently uploaded (20)

PDF
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Captain IT
 
PDF
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
PPTX
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
georgschmitzdoerner
 
PDF
DevOps & Developer Experience Summer BBQ
AUGNYC
 
PPTX
C Programming Basics concept krnppt.pptx
Karan Prajapat
 
PDF
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
SMACT Works
 
PDF
CIFDAQ's Teaching Thursday: Moving Averages Made Simple
CIFDAQ
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
AVTRON Technologies LLC
 
PDF
Test Bank, Solutions for Java How to Program, An Objects-Natural Approach, 12...
famaw19526
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
Shreyas_Phanse_Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
SHREYAS PHANSE
 
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Captain IT
 
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
madgavkar20181017ppt McKinsey Presentation.pdf
georgschmitzdoerner
 
DevOps & Developer Experience Summer BBQ
AUGNYC
 
C Programming Basics concept krnppt.pptx
Karan Prajapat
 
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
SMACT Works
 
CIFDAQ's Teaching Thursday: Moving Averages Made Simple
CIFDAQ
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
AVTRON Technologies LLC
 
Test Bank, Solutions for Java How to Program, An Objects-Natural Approach, 12...
famaw19526
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
Doc9.....................................
SofiaCollazos
 
Shreyas_Phanse_Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
SHREYAS PHANSE
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 

Intro To Mongo Db

  • 2. In This Talk…What is MongoDB?Why use it?Documents and CollectionsQueryingJavaScript ShellSchema Design
  • 4. Not a RDBMSMongo is not a relational database like MySQLNo transactionsNo referential integrityNo joinsNo schema, so no columns or rowsNoSQL
  • 5. Not a Key-Value StoreMongo is not simply a key-value store like RedisStores structured dataRich query interfaceIndexesMap/ReduceAutomatic sharding, GridFS, geospatial indexing, etc.
  • 6. Document-oriented DatabaseRecords are JSON documents (actually BSON)Stored in collectionsNo predefined schemaDocs in the same collection don’t even need to have the same fieldsAtomic in-place operators for contention-free updates$set, $inc, $push, $pop, etc.
  • 7. Mongo Documentuser = { name: "Frank Furter", occupation: "A scientist", location: "Transylvania" }
  • 9. It’s Stupid Fast!Anywhere from 2 to 10 times faster than MySQLDepends on which contrived benchmark you’re looking atHere’s one I just made up:
  • 10. It’s Stupid Fast!About 50 times faster than CouchDBAccording to http://www.idiotsabound.com/did-i-mention-mongodb-is-fast-way-to-go-mongo2 important points:It’s pretty quickBenchmarks are worthless unless you do them on your actual workload
  • 11. It’s Web Scale!Sharding built-in, automatic, and *Just Works™*Just Works™ guarantee applies only if you have a cluster of shard replica sets with config servers and routing servers and you define your own shard key(s) with appropriate uniformity and granularityAsynchronous replication for failover and redundancy
  • 12. It’s Pretty PainlessSchemalessNo more configuring database columns with typesNo more defining and managing migrationsJust stick your data in there, it’s fineNoSQLORMs exist mostly because writing SQL sucksMongo’s query language is basically JSONThe Mongo driver for your favorite language is really nice and officially supportedHandy JavaScript shell for the CLI
  • 13. It’s Pretty PainlessMySQL/* First go create the database, the table, the schema, etc. */mysql_connect("localhost", "username", "password") or die(mysql_error());mysql_select_db("test") or die(mysql_error());$sql = "INSERT INTO users (name, age) VALUES ('Janet', 23)";mysql_query($sql);$result = mysql_query("SELECT * FROM users WHERE age = 23");$row = mysql_fetch_assoc($result);echo "Oh, " . $row['name'] . "!"; // prints "Oh, Janet!"MongoDB$mongo = new Mongo(); // defaults to localhost with no auth$users = $mongo->test_db->users; // database and collection created implicitly$users->insert( array('name' => 'Brad', 'age' => 25) );$user = $users->findOne( array('age' => 25) );echo "Oh, " . $user->name . "!"; // prints "Oh, Brad!"
  • 14. All the Cool Kids Are Doing Ithttp://www.mongodb.org/display/DOCS/Production+Deployments
  • 16. Documents and CollectionsDocuments are the recordsLike objects in OOP, or rows in RDBMSCollections are groups of documentsUsually represent a top-level class in your appHeterogeneous setUnlike RDBMS tables, no predefined schemaNo foreign keys, so how do we reference other objects?Don't! Just embed the sub-item in the parent docOr, use a key for references and deal with the fact that you don't get integrity or joins
  • 17. Embedded ObjectsDocuments can embed other documentsUsed to efficiently represent a relationFor example:{ name: 'Brad Majors', address: { street: 'Oak Terrace', city: 'Denton' }}
  • 19. QueriesQueries are documentsQuery expression objects indicate a pattern to matchdb.users.find( {last_name: 'Smith'} )Several query objects for advanced queriesdb.users.find( {age: {$gte: 23} } )db.users.find( {age: {$in: [23,25]} } )
  • 20. Querying Embedded ObjectsExact match an entire embedded objectdb.users.find( {address: {street: 'Oak Terrace', city: 'Denton'}} )Dot-notation for a partial matchdb.users.find( {"address.city": 'Denton'} )
  • 22. JS ShellComes with MongoDBLaunch it with 'mongo' on the command-lineTry a simplified version at http://www.mongodb.org/Great fit since Mongo docs are basically JSON
  • 23. Live DemoIf the tech demo gods allow it
  • 25. I thought you said no schema?There is no predefined schemaYour application creates an ad-hoc schema with the objects it createsThe schema is implicit in the queries your application runs
  • 26. Schema DesignUse collections to represent the top-level classes of your applicationBut don't just make a collection for every object typeThese aren't like tables in an RDBMSLess normalization, more embedding
  • 27. Obligatory Blog Post ExampleA blog post has an author, some text, and many commentsThe comments are unique per post, but one author has many postsHow would you design this in SQL?Let's look at how we might design it in Mongo
  • 28. Bad Schema Design: ReferencesCollections for posts, authors, and commentsReferences by manually created IDpost = { id: 150, author: 100, text: 'This is a pretty awesome post.', comments: [100, 105, 112]}author = { id: 100, name: 'Michael Arrington' posts: [150]}comment = { id: 105, text: 'Whatever this sux.'}
  • 29. Better Schema Design: EmbeddingCollection for postsEmbed comments, author namepost = { author: 'Michael Arrington', text: 'This is a pretty awesome post.', comments: [ 'Whatever this post sux.', 'I agree, lame!' ]}
  • 30. BenefitsEmbedded objects brought back in the same query as parent objectOnly 1 trip to the DB server requiredObjects in the same collection are generally stored contiguously on diskSpatial locality = fasterIf the document model matches your domain well, it can be much easier to comprehend than nasty joins
  • 31. IndexesMongo supports indexes to greatly improve query performanceNo need to create in advanceCreate idempotent indexes in your app with "ensure_index"
  • 32. Schema Design LimitationsNo referential integrityHigh degree of denormalization means updating something in many places instead of oneLack of predefined schema is a double-edged swordHopefully you have a model in your appObjects within a collection can be completely inconsistent in their fields
  • 34. Final ThoughtsMongoDB is fast no matter how you slice itIt achieves high performance by literally playing fast and loose with your dataThat's not necessarily a bad thing, just a tradeoffVery rapid development, open sourceDocument model is simple but powerfulAdvanced features like map/reduce, geospatial indexing etc. are very compellingSurprisingly great drivers for most languages
  • 36. Thanks!These slides are online:http://bit.ly/intro_to_mongo