SlideShare a Scribd company logo
Dev Jumpstart: Building Your First App
Building Your First App With MongoDB
Andrew Erlichson,
Vice President of Engineering
Developer Experience
What is MongoDB
4
Document Database
• Not for .PDF & .DOC files
• A document is essentially an associative array
• Document == JSON object
• Document == PHP Array
• Document == Python Dict
• Document == Ruby Hash
• etc
5
Terminology
RDBMS MongoDB
Table, View ➜ Collection
Row ➜ Document
Index ➜ Index
Join ➜ Embedded Document
Foreign Key ➜ Reference
Partition ➜ Shard
6
Open Source
• MongoDB is an open source project
• https://www.github.com/mongodb
• Started & sponsored by MongoDB, Inc.
• Licensed under the AGPL
• Commercial licenses available
• Contributions welcome
7
Horizontally Scalable
8
Database Landscape
9
Full Featured
• Ad Hoc queries
• Real time aggregation
• Rich query capabilities
• Geospatial features
• Support for most programming languages
• Flexible schema
10
http://www.mongodb.org/downloads
1
2
11
Andrews-MacBook:Downloads aje$ tar xvf mongodb-osx-x86_64-3.0.3.tgz
x mongodb-osx-x86_64-3.0.3/README
x mongodb-osx-x86_64-3.0.3/THIRD-PARTY-NOTICES
x mongodb-osx-x86_64-3.0.3/GNU-AGPL-3.0
x mongodb-osx-x86_64-3.0.3/bin/mongodump
x mongodb-osx-x86_64-3.0.3/bin/mongorestore
x mongodb-osx-x86_64-3.0.3/bin/mongoexport
x mongodb-osx-x86_64-3.0.3/bin/mongoimport
x mongodb-osx-x86_64-3.0.3/bin/mongostat
x mongodb-osx-x86_64-3.0.3/bin/mongotop
x mongodb-osx-x86_64-3.0.3/bin/bsondump
x mongodb-osx-x86_64-3.0.3/bin/mongofiles
x mongodb-osx-x86_64-3.0.3/bin/mongooplog
x mongodb-osx-x86_64-3.0.3/bin/mongoperf
x mongodb-osx-x86_64-3.0.3/bin/mongosniff
x mongodb-osx-x86_64-3.0.3/bin/mongod
x mongodb-osx-x86_64-3.0.3/bin/mongos
x mongodb-osx-x86_64-3.0.3/bin/mongo
Unpacking the Tarball
$ cd mongodb-osx-x86_64-3.0.3/bin
$ mkdir –p /data/db
$ ./mongod
Running MongoDB
aje-desktop:bin aje$ ./mongod
2015-05-28T09:45:41.621-0400 I JOURNAL [initandlisten] journal dir=/data/db
2015-05-28T09:45:41.621-0400 I JOURNAL [initandlisten] recover : no journal files present, no recovery needed
2015-05-28T09:45:41.638-0400 I JOURNAL [durability] Durability thread started
2015-05-28T09:45:41.638-0400 I CONTROL [initandlisten] MongoDB starting : pid=17522 port=27017 64-bit host=aje-
desktop
2015-05-28T09:45:41.638-0400 I JOURNAL [journal writer] Journal writer thread started
2015-05-28T09:45:41.638-0400 I CONTROL [initandlisten] db version v3.0.3
2015-05-28T09:45:41.638-0400 I CONTROL [initandlisten] git version: b40106b36eecd1b4407eb1ad1af6bc60593c6105
2015-05-28T09:45:41.638-0400 I CONTROL [initandlisten] build info: Darwin bs-osx108-7 12.5.0 Darwin Kernel Version
12.5.0: Sun Sep 29 13:33:47 PDT 2013; root:xnu-2050.48.12~1/RELEASE_X86_64 x86_64 BOOST_LIB_VERSION=1_49
2015-05-28T09:45:41.638-0400 I CONTROL [initandlisten] allocator: system
2015-05-28T09:45:41.638-0400 I CONTROL [initandlisten] options: {}
2015-05-28T09:45:41.647-0400 I NETWORK [initandlisten] waiting for connections on port 27017
Log Output from mongod
aje-desktop:bin aje$ ./mongo
MongoDB shell version: 3.0.3
connecting to: 127.0.0.1:7=27017/test
> db.names.insert({'fullname':'Andrew Erlichson’})
WriteResult({ "nInserted" : 1 })
> db.names.findOne()
{
"_id" : ObjectId("55671da150a222c93b33bca7"),
"fullname" : "Andrew Erlichson",
}
>
Inserting Your First Document
16
Web Demo
• MongoDB
• Python
• Bottle web framework
• Pymongo
$ sudo easy_install pip
$ sudo pip install pymongo
$ sudo pip install
Python Prerequisites
from pymongo import MongoClient
from bottle import route, run, template
@route('/')
def index():
collection = db.names
doc = collection.find_one()
return "Hello " + doc['fullname']
client = MongoClient('localhost', 27017)
db = client.test
run(host='localhost', port=8080)
hello.py
@route('/')
def index():
collection = db.names
doc = collection.find_one()
return "Hello " + doc['fullname’]
client = MongoClient('localhost', 27017)
db = client.test
run(host='localhost', port=8080)
hello.py
Import the modules needed for Pymongo
and the bottle web framework
from pymongo import MongoClient
from bottle import route, run, template
@route('/')
def index():
collection = db.names
doc = collection.find_one()
return "Hello " + doc['fullname']
run(host='localhost', port=8080)
hello.py
Connect to the MongoDB Database
on Localhost and use the “test”
database
from pymongo import MongoClient
from bottle import route, run, template
@route('/')
def index():
collection = db.names
doc = collection.find_one()
return "Hello " + doc['fullname']
client = MongoClient('localhost', 27017)
db = client.test
run(host='localhost', port=8080)
hello.py
Define a handler that runs when user hits the
root of our web servers. That handler does a
single query to the database and prints back
to the web browser
from pymongo import MongoClient
from bottle import route, run, template
@route('/')
def index():
collection = db.names
doc = collection.find_one()
return "Hello " + doc['fullname']
client = MongoClient('localhost', 27017)
db = client.test
hello.py
Start the webserver on locahost,
listening on port 8080
Our First App
Let’s Design a Blog
Determine Your Entities
First Step In Your App
26
Entities in our Blogging System
• Users (post authors)
• Posts
• Comments
• Tags
We Would Start By Doing Schema Design
In a relational based app
28
Typical (relational) ERD
tag_id
tag
tags
post_id
post_title
body
post_date
post_author_uid
post_id
comment_id
comment
author_name
comment_date
author_email
uid
username
password
Email
post_id
tag_id
users
posts comments
post_tags
In MongoDB
We Start By Building Our App
And Let The Schema Evolve
30
MongoDB ERD
title
body
date
username
Posts
[ ] comments
[ ] tags
Username
password
email
Users
Manipulating Blog Data
(mongo shell version)
user = {
_id: ’erlichson',
"password" :
"a7cf1c46861b140894e1371a0eb6cd6791ca2e339f1a8d83a1846f6c811
41dec,zYJue",
,
email: ’andrew@mongodb.com',
}
Start with an object
(or array, hash, dict, etc)
> db.users.insert(user)
Insert the record
No collection creation needed
> db.users.findOne()
{
"_id" : "erlichson",
"password" :
"a7cf1c46861b140894e1371a0eb6cd6791ca2e339f1a8d83a1846f6c81141dec,zYJue",
"email" : “aje@10gen.com”
}
Querying for the user
> db.posts.insert({
title: ‘Hello World’,
body: ‘This is my first blog post’,
date: new Date(‘2013-06-20’),
username: ‘erlichson’,
tags: [‘adventure’, ‘mongodb’],
comments: []
})
Creating a blog post
 db.posts.find().pretty()
"_id" : ObjectId("51c3bafafbd5d7261b4cdb5a"),
"title" : "Hello World",
"body" : "This is my first blog post",
"date" : ISODate("2013-06-20T00:00:00Z"),
"username" : "erlichson",
"tags" : [
"adventure",
"mongodb"
],
"comments" : [ ]
}
Finding the Post
> db.posts.find({tags:'adventure'}).pretty()
{
"_id" : ObjectId("51c3bcddfbd5d7261b4cdb5b"),
"title" : "Hello World",
"body" : "This is my first blog post",
"date" : ISODate("2013-06-20T00:00:00Z"),
"username" : "erlichson",
"tags" : [
"adventure",
"mongodb"
],
"comments" : [ ]
}
Querying an Array
> db.posts.update({_id:
new ObjectId("51c3bcddfbd5d7261b4cdb5b")},
{$push:{comments:
{name: 'Steve Blank', comment: 'Awesome Post'}}})
>
Using Update to Add a Comment
> {_id:
new ObjectId("51c3bcddfbd5d7261b4cdb5b")},
>
Using Update to Add a Comment
Predicate of the query. Specifies which
document to update
> db.posts.update({_id:
new ObjectId("51c3bcddfbd5d7261b4cdb5b")},
{$push:{comments:
{name: 'Steve Blank', comment: 'Awesome Post'}}})
>
Using Update to Add a Comment
“push” a new document under the
“comments” array
> db.posts.findOne({_id: new ObjectId("51c3bcddfbd5d7261b4cdb5b")})
{
"_id" : ObjectId("51c3bcddfbd5d7261b4cdb5b"),
"body" : "This is my first blog post",
"comments" : [
{
"name" : "Steve Blank",
"comment" : "Awesome Post"
}
],
"date" : ISODate("2013-06-20T00:00:00Z"),
"tags" : [
"adventure",
"mongodb"
],
"title" : "Hello World",
"username" : "erlichson"
}
Post with Comment Attached
MongoDB Drivers
43
Dev Jumpstart: Building Your First App
Next Steps
46
http://docs.mongodb.org/ecosystem/drivers/
Dev Jumpstart: Building Your First App
Dev Jumpstart: Building Your First App

More Related Content

PPTX
Dev Jumpstart: Build Your First App with MongoDB
PPTX
Building Your First Application with MongoDB
PDF
Mongoid in the real world
PPTX
Academy PRO: Elasticsearch. Data management
PDF
Learn Learn how to build your mobile back-end with MongoDB
KEY
MongoDB & Mongoid with Rails
PPTX
Hack ASP.NET website
PDF
Building Client-Side Attacks with HTML5 Features
Dev Jumpstart: Build Your First App with MongoDB
Building Your First Application with MongoDB
Mongoid in the real world
Academy PRO: Elasticsearch. Data management
Learn Learn how to build your mobile back-end with MongoDB
MongoDB & Mongoid with Rails
Hack ASP.NET website
Building Client-Side Attacks with HTML5 Features

What's hot (18)

PDF
Entity provider selection confusion attacks in JAX-RS applications
PDF
Enabling Java 2 Runtime Security with Eclipse Plug-ins - Ted Habeck, Advisory...
PDF
Connect.Tech- Aqueduct: A server-side framework in Dart
PDF
Automating Django Functional Tests Using Selenium on Cloud
PDF
2013-08-08 | Mantle (Cocoaheads Vienna)
PPTX
Misconfigured CORS, Why being secure isn't getting easier. AppSec USA 2016
PPTX
Building APIs with MVC 6 and OAuth
PPTX
TO Hack an ASP .NET website?
PPTX
Fun with exploits old and new
PDF
APIDOC In A Nutshell
PDF
Data Exploration with Elasticsearch
PPT
Mining Ruby Gem vulnerabilities for Fun and No Profit.
PDF
Denis Zhuchinski Ways of enhancing application security
PDF
ASP.NET MVC Workshop for Women in Technology
PDF
Cross-domain requests with CORS
PPTX
CORS - Enable Alfresco for CORS
PDF
Reverse Engineering iOS apps
PPTX
How to discover 1352 Wordpress plugin 0days in one hour (not really)
Entity provider selection confusion attacks in JAX-RS applications
Enabling Java 2 Runtime Security with Eclipse Plug-ins - Ted Habeck, Advisory...
Connect.Tech- Aqueduct: A server-side framework in Dart
Automating Django Functional Tests Using Selenium on Cloud
2013-08-08 | Mantle (Cocoaheads Vienna)
Misconfigured CORS, Why being secure isn't getting easier. AppSec USA 2016
Building APIs with MVC 6 and OAuth
TO Hack an ASP .NET website?
Fun with exploits old and new
APIDOC In A Nutshell
Data Exploration with Elasticsearch
Mining Ruby Gem vulnerabilities for Fun and No Profit.
Denis Zhuchinski Ways of enhancing application security
ASP.NET MVC Workshop for Women in Technology
Cross-domain requests with CORS
CORS - Enable Alfresco for CORS
Reverse Engineering iOS apps
How to discover 1352 Wordpress plugin 0days in one hour (not really)
Ad

Similar to Dev Jumpstart: Building Your First App (20)

PPTX
Webinar: Building Your First App
PPTX
Building Your First App with Shawn Mcarthy
PPTX
Dev Jumpstart: Build Your First App with MongoDB
PDF
Building your first app with mongo db
PDF
Building your first app with MongoDB
PPTX
Dev Jumpstart: Build Your First App with MongoDB
PPTX
Back to Basics, webinar 2: La tua prima applicazione MongoDB
PPTX
Dev Jumpstart: Build Your First App with MongoDB
PDF
Mongo db eveningschemadesign
PPTX
Webinar: Building Your First MongoDB App
PDF
MongoDB Introduction talk at Dr Dobbs Conference, MongoDB Evenings at Bangalo...
PDF
Parse cloud code
PPTX
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
PPTX
Back to Basics Webinar 2: Your First MongoDB Application
PPTX
Back to Basics Webinar 2 - Your First MongoDB Application
PDF
오픈 소스 프로그래밍 - NoSQL with Python
PDF
Back to Basics 2017: Mí primera aplicación MongoDB
PPTX
Mongodb ExpressJS HandlebarsJS NodeJS FullStack
PPTX
Webinar: What's new in the .NET Driver
PDF
MongoDB
Webinar: Building Your First App
Building Your First App with Shawn Mcarthy
Dev Jumpstart: Build Your First App with MongoDB
Building your first app with mongo db
Building your first app with MongoDB
Dev Jumpstart: Build Your First App with MongoDB
Back to Basics, webinar 2: La tua prima applicazione MongoDB
Dev Jumpstart: Build Your First App with MongoDB
Mongo db eveningschemadesign
Webinar: Building Your First MongoDB App
MongoDB Introduction talk at Dr Dobbs Conference, MongoDB Evenings at Bangalo...
Parse cloud code
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
Back to Basics Webinar 2: Your First MongoDB Application
Back to Basics Webinar 2 - Your First MongoDB Application
오픈 소스 프로그래밍 - NoSQL with Python
Back to Basics 2017: Mí primera aplicación MongoDB
Mongodb ExpressJS HandlebarsJS NodeJS FullStack
Webinar: What's new in the .NET Driver
MongoDB
Ad

More from MongoDB (20)

PDF
MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
PDF
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
PDF
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
PDF
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
PDF
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
PDF
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
PDF
MongoDB SoCal 2020: MongoDB Atlas Jump Start
PDF
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
PDF
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
PDF
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
PDF
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
PDF
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
PDF
MongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
PDF
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
PDF
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
PDF
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
PDF
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
PDF
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
PDF
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
PDF
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
MongoDB SoCal 2020: MongoDB Atlas Jump Start
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
MongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...

Recently uploaded (20)

PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PPT
Teaching material agriculture food technology
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Cloud computing and distributed systems.
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Approach and Philosophy of On baking technology
PDF
Encapsulation theory and applications.pdf
PDF
KodekX | Application Modernization Development
PPTX
Spectroscopy.pptx food analysis technology
Diabetes mellitus diagnosis method based random forest with bat algorithm
Review of recent advances in non-invasive hemoglobin estimation
NewMind AI Weekly Chronicles - August'25 Week I
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Reach Out and Touch Someone: Haptics and Empathic Computing
Programs and apps: productivity, graphics, security and other tools
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Spectral efficient network and resource selection model in 5G networks
Teaching material agriculture food technology
Chapter 3 Spatial Domain Image Processing.pdf
Understanding_Digital_Forensics_Presentation.pptx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Advanced methodologies resolving dimensionality complications for autism neur...
Cloud computing and distributed systems.
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Approach and Philosophy of On baking technology
Encapsulation theory and applications.pdf
KodekX | Application Modernization Development
Spectroscopy.pptx food analysis technology

Dev Jumpstart: Building Your First App

  • 2. Building Your First App With MongoDB Andrew Erlichson, Vice President of Engineering Developer Experience
  • 4. 4 Document Database • Not for .PDF & .DOC files • A document is essentially an associative array • Document == JSON object • Document == PHP Array • Document == Python Dict • Document == Ruby Hash • etc
  • 5. 5 Terminology RDBMS MongoDB Table, View ➜ Collection Row ➜ Document Index ➜ Index Join ➜ Embedded Document Foreign Key ➜ Reference Partition ➜ Shard
  • 6. 6 Open Source • MongoDB is an open source project • https://www.github.com/mongodb • Started & sponsored by MongoDB, Inc. • Licensed under the AGPL • Commercial licenses available • Contributions welcome
  • 9. 9 Full Featured • Ad Hoc queries • Real time aggregation • Rich query capabilities • Geospatial features • Support for most programming languages • Flexible schema
  • 11. 11
  • 12. Andrews-MacBook:Downloads aje$ tar xvf mongodb-osx-x86_64-3.0.3.tgz x mongodb-osx-x86_64-3.0.3/README x mongodb-osx-x86_64-3.0.3/THIRD-PARTY-NOTICES x mongodb-osx-x86_64-3.0.3/GNU-AGPL-3.0 x mongodb-osx-x86_64-3.0.3/bin/mongodump x mongodb-osx-x86_64-3.0.3/bin/mongorestore x mongodb-osx-x86_64-3.0.3/bin/mongoexport x mongodb-osx-x86_64-3.0.3/bin/mongoimport x mongodb-osx-x86_64-3.0.3/bin/mongostat x mongodb-osx-x86_64-3.0.3/bin/mongotop x mongodb-osx-x86_64-3.0.3/bin/bsondump x mongodb-osx-x86_64-3.0.3/bin/mongofiles x mongodb-osx-x86_64-3.0.3/bin/mongooplog x mongodb-osx-x86_64-3.0.3/bin/mongoperf x mongodb-osx-x86_64-3.0.3/bin/mongosniff x mongodb-osx-x86_64-3.0.3/bin/mongod x mongodb-osx-x86_64-3.0.3/bin/mongos x mongodb-osx-x86_64-3.0.3/bin/mongo Unpacking the Tarball
  • 13. $ cd mongodb-osx-x86_64-3.0.3/bin $ mkdir –p /data/db $ ./mongod Running MongoDB
  • 14. aje-desktop:bin aje$ ./mongod 2015-05-28T09:45:41.621-0400 I JOURNAL [initandlisten] journal dir=/data/db 2015-05-28T09:45:41.621-0400 I JOURNAL [initandlisten] recover : no journal files present, no recovery needed 2015-05-28T09:45:41.638-0400 I JOURNAL [durability] Durability thread started 2015-05-28T09:45:41.638-0400 I CONTROL [initandlisten] MongoDB starting : pid=17522 port=27017 64-bit host=aje- desktop 2015-05-28T09:45:41.638-0400 I JOURNAL [journal writer] Journal writer thread started 2015-05-28T09:45:41.638-0400 I CONTROL [initandlisten] db version v3.0.3 2015-05-28T09:45:41.638-0400 I CONTROL [initandlisten] git version: b40106b36eecd1b4407eb1ad1af6bc60593c6105 2015-05-28T09:45:41.638-0400 I CONTROL [initandlisten] build info: Darwin bs-osx108-7 12.5.0 Darwin Kernel Version 12.5.0: Sun Sep 29 13:33:47 PDT 2013; root:xnu-2050.48.12~1/RELEASE_X86_64 x86_64 BOOST_LIB_VERSION=1_49 2015-05-28T09:45:41.638-0400 I CONTROL [initandlisten] allocator: system 2015-05-28T09:45:41.638-0400 I CONTROL [initandlisten] options: {} 2015-05-28T09:45:41.647-0400 I NETWORK [initandlisten] waiting for connections on port 27017 Log Output from mongod
  • 15. aje-desktop:bin aje$ ./mongo MongoDB shell version: 3.0.3 connecting to: 127.0.0.1:7=27017/test > db.names.insert({'fullname':'Andrew Erlichson’}) WriteResult({ "nInserted" : 1 }) > db.names.findOne() { "_id" : ObjectId("55671da150a222c93b33bca7"), "fullname" : "Andrew Erlichson", } > Inserting Your First Document
  • 16. 16 Web Demo • MongoDB • Python • Bottle web framework • Pymongo
  • 17. $ sudo easy_install pip $ sudo pip install pymongo $ sudo pip install Python Prerequisites
  • 18. from pymongo import MongoClient from bottle import route, run, template @route('/') def index(): collection = db.names doc = collection.find_one() return "Hello " + doc['fullname'] client = MongoClient('localhost', 27017) db = client.test run(host='localhost', port=8080) hello.py
  • 19. @route('/') def index(): collection = db.names doc = collection.find_one() return "Hello " + doc['fullname’] client = MongoClient('localhost', 27017) db = client.test run(host='localhost', port=8080) hello.py Import the modules needed for Pymongo and the bottle web framework
  • 20. from pymongo import MongoClient from bottle import route, run, template @route('/') def index(): collection = db.names doc = collection.find_one() return "Hello " + doc['fullname'] run(host='localhost', port=8080) hello.py Connect to the MongoDB Database on Localhost and use the “test” database
  • 21. from pymongo import MongoClient from bottle import route, run, template @route('/') def index(): collection = db.names doc = collection.find_one() return "Hello " + doc['fullname'] client = MongoClient('localhost', 27017) db = client.test run(host='localhost', port=8080) hello.py Define a handler that runs when user hits the root of our web servers. That handler does a single query to the database and prints back to the web browser
  • 22. from pymongo import MongoClient from bottle import route, run, template @route('/') def index(): collection = db.names doc = collection.find_one() return "Hello " + doc['fullname'] client = MongoClient('localhost', 27017) db = client.test hello.py Start the webserver on locahost, listening on port 8080
  • 25. Determine Your Entities First Step In Your App
  • 26. 26 Entities in our Blogging System • Users (post authors) • Posts • Comments • Tags
  • 27. We Would Start By Doing Schema Design In a relational based app
  • 29. In MongoDB We Start By Building Our App And Let The Schema Evolve
  • 30. 30 MongoDB ERD title body date username Posts [ ] comments [ ] tags Username password email Users
  • 32. user = { _id: ’erlichson', "password" : "a7cf1c46861b140894e1371a0eb6cd6791ca2e339f1a8d83a1846f6c811 41dec,zYJue", , email: ’andrew@mongodb.com', } Start with an object (or array, hash, dict, etc)
  • 33. > db.users.insert(user) Insert the record No collection creation needed
  • 34. > db.users.findOne() { "_id" : "erlichson", "password" : "a7cf1c46861b140894e1371a0eb6cd6791ca2e339f1a8d83a1846f6c81141dec,zYJue", "email" : “aje@10gen.com” } Querying for the user
  • 35. > db.posts.insert({ title: ‘Hello World’, body: ‘This is my first blog post’, date: new Date(‘2013-06-20’), username: ‘erlichson’, tags: [‘adventure’, ‘mongodb’], comments: [] }) Creating a blog post
  • 36.  db.posts.find().pretty() "_id" : ObjectId("51c3bafafbd5d7261b4cdb5a"), "title" : "Hello World", "body" : "This is my first blog post", "date" : ISODate("2013-06-20T00:00:00Z"), "username" : "erlichson", "tags" : [ "adventure", "mongodb" ], "comments" : [ ] } Finding the Post
  • 37. > db.posts.find({tags:'adventure'}).pretty() { "_id" : ObjectId("51c3bcddfbd5d7261b4cdb5b"), "title" : "Hello World", "body" : "This is my first blog post", "date" : ISODate("2013-06-20T00:00:00Z"), "username" : "erlichson", "tags" : [ "adventure", "mongodb" ], "comments" : [ ] } Querying an Array
  • 38. > db.posts.update({_id: new ObjectId("51c3bcddfbd5d7261b4cdb5b")}, {$push:{comments: {name: 'Steve Blank', comment: 'Awesome Post'}}}) > Using Update to Add a Comment
  • 39. > {_id: new ObjectId("51c3bcddfbd5d7261b4cdb5b")}, > Using Update to Add a Comment Predicate of the query. Specifies which document to update
  • 40. > db.posts.update({_id: new ObjectId("51c3bcddfbd5d7261b4cdb5b")}, {$push:{comments: {name: 'Steve Blank', comment: 'Awesome Post'}}}) > Using Update to Add a Comment “push” a new document under the “comments” array
  • 41. > db.posts.findOne({_id: new ObjectId("51c3bcddfbd5d7261b4cdb5b")}) { "_id" : ObjectId("51c3bcddfbd5d7261b4cdb5b"), "body" : "This is my first blog post", "comments" : [ { "name" : "Steve Blank", "comment" : "Awesome Post" } ], "date" : ISODate("2013-06-20T00:00:00Z"), "tags" : [ "adventure", "mongodb" ], "title" : "Hello World", "username" : "erlichson" } Post with Comment Attached
  • 43. 43

Editor's Notes

  • #4: First what is MongoDB? What are its salient properties?
  • #5: By documents we don’t mean microsoft word documents or pdf files. You can think of a document as an associative array. If you use javascript, a JSON object can be stored directly into MongoDB. If you are familiat with PHP, it’s stores stuff that looks like a php array. In python, the dict is the closest analogy. And in ruby, there is a ruby hash. As you know if you use thee things, they are not flat data structures. They are hierarchical data structures. For for example, in python you can store an array within a dict, and each array element could be another array or a dict. This is really the fundamental departure from relational where you store rows, and the rows are flat.
  • #6: If you come from the world of relational, it’s useful to go through the different concept in a relational database and think about how they map to mongodb. In relational, you have a table, or perhaps a view on a table. In mongodb, we have collections. In relational, a table holds rows. In mongodb, a collection holds documents. Indexes are very similar in both technologies. In relational you can create compound indexes that include multiple columns. In mongodb, you can create indexes that include multiple keys. Relational offers the concept of a join. In mongodb, we don’t support joins, but you can “pre-join” your data by embedding documents as values. In relational, you have foreign keys, mongodb has references between collections. In relational, you might talk about partitioning the database to scale. We refer to this as sharding.
  • #7: AGPL – GNU Affero General Public License. MongoDB is open source. You can download the source right now on github. We license it under the Affero variant of the GPL. The project was initiated and is sponsored by MongoDB. You can get a commercial license by buying a subscription from MongoDB. Subscribers also receive commercial support and depending on the subscription level, access to some proprietary extensions, mostly interesting to enterprises. Contributions to the source are welcome.
  • #8: One of the primary design goals of MongoDB is that it be horizontally scalable. With a traditional RDBMS, when you need to handler a larger workload, you buy a bigger machine. The problem with that approach is that machines are not priced linearly. The largest computers cost exponentially more money than commodity hardware. And what’s more, if you have reasonable success in your business, you can quickly get to a point where you simply can’t buy a large enough a machine for the workload. MongoDB was designed be horizontally scalable through sharding by adding boxes.
  • #9: Well how did we achieve this horizontal scalability. If you think about the database landscape, you can plot each technology in terms of its scalability and its depth of functionality. At the top left we have the key value stores like memcached. These are typically very fast, but they lack key features to make a developer productive. On the far right, are the traditional RDBMS technologies like Oracle and Mysql. These are very full featured, but will not scale easily. And the reason that they won’t scale is that certain features they support, such as joins between tables and transactions, are not easy to run in parallel across multiple computers. MongoDB strives to sit at the knee of the curve, achieving nearly the as much scalability as key value stores, while only giving up the features that prevent scaling. So, as I said, mongoDB does not support joins or transactions. But we have certain compensating features, mostly beyond the scope of this talk, that mitigate the impact of that design decision.
  • #10: But we left a lot of good stuff in, including everything you see here. Ad hoc queries means that you can explore data from the shell using a query language (not sql though). Real time aggregation gives you much of the functionality offered by group by in sql. We have a strong consistency model by default. What that means is that you when you read data from the datbase, you read what you wrote. Sounds fairly obvious, but some systems don’t offer that feature to gain greater availability of writes. We have geospatial queries, the ability to find things based on location. And as you will see we support all popular programming languages and offer flexible, dynamic schema.
  • #14: To get mongodb started, you download the tarball, expand it, cd to the directory. Create a data directory in the standard place. Now start mongodb running. That’s it.
  • #15: To get mongodb started, you download the tarball, expand it, cd to the directory. Create a data directory in the standard place. Now start mongodb running. That’s it.
  • #16: To get mongodb started, you The first thing you will want to do after that is start the mongos hell. The mongo shell is an interaactive program that connects to mongodb and lets you perform ad-hoc queries against the database. Here you can see we have started the mongodb shell. Then we insert our first document into a collection called test. That document has a single key called “text” and it’s value is “welcome to mongodb”.’ Right after inserting it, we query the test collection and print out every document in it. There is only one, just he one we created. Plus you can see there is a strange _id field that is now part of the document. We will tallk more about that later, but the short explanation is that every document must have a unique _id value and if you don’t specify one, Mongo creates one for you. download the tarball, expand it, cd to the directory. Create a data directory in the standard place. Now start mongodb running. That’s it.
  • #26: Ok, the first step in building an application to manage this library is to think about what entities we need to model and maintain.
  • #27: The entities for our blog will be users, and by users we mean the authors of the blog posts. We will let people comment anonymously. We also have comments and tags.
  • #28: In a relational based solution, we would probably start by doing schema design. We would build out an ERD diagram.
  • #29: Here is the entity relationship diagram for a small blogging system. Each of these boxes represents a relational table you might have a user table, and a posts table, which holds the blog posts, and tag table, and so on. In all, if you count the tables used to relate these tables, there would be 5 tables. Let’s look at the posts table. For each post you would assign a post_id. When a comment comes in, you would put it in the comments table and also store the post_id. The post_tags table relates a post and its tags. Posts and tags are a many to many relationship. To display the front page of the blog you would need to access every table.
  • #30: In mongodb this process is turned on its head. We would do some basic planning on the collections and the document structure that would be typical in each collection and then immediately get to work on the application, letting the schema evolve over time. In mongo, every document in a collection does not need to have the same schema, although usually documents in the same collection have very nearly the same schema by convention.
  • #31: In MongoDB, you might model this blogging system with only two collections. A user collection that would hold information about the users in the system and a article collection that would embed comments, tags and category information right in the article. This way of representing the data has the benefit of being a lot closer to the way you model it within most object oriented programming languages. Rather than having to select from 8 tables to reconstruct an article, you can do a single query. Let’s stop and pause and look at this closely. The idea of having an array of comments within a blog post is a fundamental departure from relational. There are some nice properties to this. First, when I fetch the post I get every piece of information I need to display it. Second, it’s fast. Disks are slow to seek but once you seek to a location, they have a lot of throughput.
  • #32: Now I would like to turn to working within data within mongodb for blog application.
  • #33: Here is a what a document looks like in javascript object notation, or JSON. Note that the document begins with a leading parentheseis, and then has a sequence of key/value pairs. They keys are not protected by quotes. They are optional within the shell. The values are protected by quotes. In this case we have specified strings. I am inserting myself into the users collection. This is the mongo shell, which is a full javascript interpreter, so I have assigned the json document to a variable.
  • #34: To insert the user into mongodb, we type db.users. Insert(user) in the shell. This will create a new document in the users collection. Note that I did not create the collection before I used it. MongoDB will automatically create the collection when I first use it.
  • #35: If we want to retrieve that document from mongodb using the shell, we would issue the findOne command. The findOne command without any parameters will find any one document within mongodb – and you can’t specify which one. but in this case, we only have one document within the collection and hence get the one we inserted. Note that the document now has an _id field field. Let’s talk more about that. Every document must have an _id key. If you don’t specify one, the database will insert one fore you. The default type is an ObjectID, which is a 12 byte field containing information about the time, a sequence number, which client machine and which process made the request. The _id inserted by the database is guaranteed to be unique. You can specify your own _id if you desire.
  • #36: Now it’s time to put our first blog post into the blogging system.. For our first post, we are going to say “hello world.”. Note that because we are in the mongo shell, which supports javascript, I can create a new Date object to insert the current date and time. We’ve done this w/o specifying previously what the blog collection is going to look like. This is true agile development. If we decide later to start tracking the IP address where the blog post came from, we can do that for new posts without fixing up the existing data. Of course, our application needs to understand that some keys may not be in all documents.
  • #37: Once we insert a post, the first thing we want to do is find it and make sure its there. There is only one post in the collection today so finding it is easy. We use the find command and append .pretty() on the end to so that the mongo shell prints the document in a way that is easy for humans to read. Note again that there is now an _id field for the blog post, ending in DB5A. I also inserted an emtpy comments array to make it easy to add comments later. But I could have left this out.
  • #38: Now that we have a blog post inserted, let’s look at how we would query for all blog posts that have a particular tag. This query shows the syntex for querying posts that have the tag “adventure.” This illustrates two things: first, how to query by example and second, that you can reach into an array to find a match. In this case, the query is returning all documents with elements that match the string “adventure”
  • #39: Now Let’s add a comment to the blog post. This would probably happen through a web server. For example, the user might see a post and comment on it, submitting the comment. Let’s imagine that steve blank came to my blog and posted the comment “Awesome Post.” The application server would then update the particular blog post. This query shows the syntax for an update. We specify the blog post through its _id. The ObjectID that I am creating in the shell is a throw-away data structure so that I can represent this binary value from javascript. Next, I use the $push operator to append a document to the end of the comments array. There is a rich set of query operators that start with $ within mongodb. This query appends the document with the query on the of the comments array for the blog post in question.
  • #40: Now Let’s add a comment to the blog post. This would probably happen through a web server. For example, the user might see a post and comment on it, submitting the comment. Let’s imagine that steve blank came to my blog and posted the comment “Awesome Post.” The application server would then update the particular blog post. This query shows the syntax for an update. We specify the blog post through its _id. The ObjectID that I am creating in the shell is a throw-away data structure so that I can represent this binary value from javascript. Next, I use the $push operator to append a document to the end of the comments array. There is a rich set of query operators that start with $ within mongodb. This query appends the document with the query on the of the comments array for the blog post in question.
  • #41: Now Let’s add a comment to the blog post. This would probably happen through a web server. For example, the user might see a post and comment on it, submitting the comment. Let’s imagine that steve blank came to my blog and posted the comment “Awesome Post.” The application server would then update the particular blog post. This query shows the syntax for an update. We specify the blog post through its _id. The ObjectID that I am creating in the shell is a throw-away data structure so that I can represent this binary value from javascript. Next, I use the $push operator to append a document to the end of the comments array. There is a rich set of query operators that start with $ within mongodb. This query appends the document with the query on the of the comments array for the blog post in question.
  • #42: Of course, the first thing we want to do is query to make sure our comment is in the post. We do this by using findOne, which returns one documents, and specifying the document with the same _id. The comment is within the document in yellow. Note that mongodb has decided to move the comment key within the document. This makes the point that the exact order of keys within a document is not guaranteed.
  • #43: If this was a real application it would have a front end UI and that UI would not be having the user login to the mongo shell.
  • #44: There are drivers that are created and maintained by 10gen for most popular languages. You can find them at api.mongodb.org.
  • #45: There are also drivers maintained by the community. Drivers connect to the mongodb servers. They translate BSON into native types within the language. Also take care of maintaining connections to replica set. The mongo shell that I showed you today is not a driver, but works like one in some ways. You install a driver by going to api.mongodb.org, clicking through the documentation for a driver and finding the recommended way to install it on your computer. For example, for the python driver, you use pip to install it, typically.
  • #46: We’ve covered a lot of ground in a pretty short time but still have barely scratched the surface of how to build an application within mongodb. To learn more about mongodb, you can use the online documentation, which is a great resource.