SlideShare a Scribd company logo
Building Your First App with Shawn Mcarthy
Building Your First App With MongoDB
Shawn McCarthy
Solutions Architect
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
Shawns-MacBook-Pro:~ shawn$ tar xvf ./Downloads/mongodb-osx-x86_64-3.0.4.tgz
x mongodb-osx-x86_64-3.0.4/README
x mongodb-osx-x86_64-3.0.4/THIRD-PARTY-NOTICES
x mongodb-osx-x86_64-3.0.4/GNU-AGPL-3.0
x mongodb-osx-x86_64-3.0.4/bin/mongodump
x mongodb-osx-x86_64-3.0.4/bin/mongorestore
x mongodb-osx-x86_64-3.0.4/bin/mongoexport
x mongodb-osx-x86_64-3.0.4/bin/mongoimport
x mongodb-osx-x86_64-3.0.4/bin/mongostat
x mongodb-osx-x86_64-3.0.4/bin/mongotop
x mongodb-osx-x86_64-3.0.4/bin/bsondump
x mongodb-osx-x86_64-3.0.4/bin/mongofiles
x mongodb-osx-x86_64-3.0.4/bin/mongooplog
x mongodb-osx-x86_64-3.0.4/bin/mongoperf
x mongodb-osx-x86_64-3.0.4/bin/mongosniff
x mongodb-osx-x86_64-3.0.4/bin/mongod
x mongodb-osx-x86_64-3.0.4/bin/mongos
x mongodb-osx-x86_64-3.0.4/bin/mongo
Unpacking the Tarball
$ cd mongodb-osx-x86_64-3.0.3/bin
$ sudo mkdir –p /data/db
$ sudo chown -R shawn:staff /data
$ ./mongod
Running MongoDB
Shawns-MacBook-Pro:bin shawn$ ./mongod
2015-07-18T18:36:48.814-0400 I JOURNAL [initandlisten] journal dir=/data/db/journal
2015-07-18T18:36:48.815-0400 I JOURNAL [initandlisten] recover : no journal files present, no recovery needed
2015-07-18T18:36:48.836-0400 I JOURNAL [durability] Durability thread started
2015-07-18T18:36:48.836-0400 I JOURNAL [journal writer] Journal writer thread started
2015-07-18T18:36:48.837-0400 I CONTROL [initandlisten] MongoDB starting : pid=27923 port=27017 dbpath=/data/db 64-
bit host=Shawns-MacBook-Pro.local
2015-07-18T18:36:48.837-0400 I CONTROL [initandlisten]
2015-07-18T18:36:48.837-0400 I CONTROL [initandlisten] ** WARNING: soft rlimits too low. Number of files is 256, should
be at least 1000
2015-07-18T18:36:48.837-0400 I CONTROL [initandlisten] db version v3.0.4
2015-07-18T18:36:48.837-0400 I CONTROL [initandlisten] git version: 0481c958daeb2969800511e7475dc66986fa9ed5
2015-07-18T18:36:48.837-0400 I CONTROL [initandlisten] build info: Darwin mci-osx108-11.build.10gen.cc 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-07-18T18:36:48.837-0400 I CONTROL [initandlisten] allocator: system
2015-07-18T18:36:48.837-0400 I CONTROL [initandlisten] options: {}
2015-07-18T18:36:48.842-0400 I INDEX [initandlisten] allocating new ns file /data/db/local.ns, filling with zeroes...
2015-07-18T18:36:48.899-0400 I STORAGE [FileAllocator] allocating new datafile /data/db/local.0, filling with zeroes...
2015-07-18T18:36:48.899-0400 I STORAGE [FileAllocator] creating directory /data/db/_tmp
2015-07-18T18:36:49.070-0400 I STORAGE [FileAllocator] done allocating datafile /data/db/local.0, size: 64MB, took 0.17
secs
2015-07-18T18:36:49.196-0400 I NETWORK [initandlisten] waiting for connections on port 27017
Log Output from mongod
Shawns-MacBook-Pro:bin shawn$ ./mongo
MongoDB shell version: 3.0.4
connecting to: 127.0.0.1:7=27017/test
> db.names.insert({'fullname':’Shawn McCarthy’})
WriteResult({ "nInserted" : 1 })
> db.names.findOne()
{
"_id" : ObjectId("55aad5d2795e9e59af9b375d"),
"fullname" : ”Shawn McCarthy",
}
>
Inserting Your First Document
16
Web Demo
• MongoDB
• Python
• Bottle web framework
• Pymongo
$ sudo easy_install pip
$ sudo pip install pymongo
$ sudo pip install bottle
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
Import the modules needed for Pymongo
and the bottle web framework
Connect to the MongoDB Database
on Localhost and use the “test”
database
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
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
22
Entities in our Blogging System
• Users (post authors)
• Posts
• Comments
• Tags
We Would Start By Doing Schema Design
In a relational based app
24
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
26
MongoDB ERD
title
body
date
username
Posts
[ ] comments
[ ] tags
Username
password
email
Users
Manipulating Blog Data
(mongo shell version)
user = {
_id: ’mccarthy',
password: ‘XXXXX’,
email: ’shawn.mccarthy@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" : ”mccarthy",
"password" : ”XXXXX",
"email" : “shawn.mccarthy@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: ‘mccarthy’,
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" : ”mccarthy",
"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" : ”mccarthy",
"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
Predicate of the query. Specifies which
document to update
“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" : ”mccarthy"
}
Post with Comment Attached
MongoDB Drivers
37
Building Your First App with Shawn Mcarthy
Next Steps
40
http://docs.mongodb.org/ecosystem/drivers/
Building Your First App with Shawn Mcarthy
Building Your First App with Shawn Mcarthy

More Related Content

PPTX
MongoDB - External Authentication
Jason Terpko
 
PPTX
Webinar: Building Your First App
MongoDB
 
PPTX
Back to Basics: My First MongoDB Application
MongoDB
 
PPTX
Search and analyze data in real time
Rohit Kalsarpe
 
PDF
Tech Talk - Blockchain presentation
Laura Steggles
 
PDF
Webinar: Was ist neu in MongoDB 2.4
MongoDB
 
PPTX
MongoDB: Comparing WiredTiger In-Memory Engine to Redis
Jason Terpko
 
PPTX
Webinar: Building Your First MongoDB App
MongoDB
 
MongoDB - External Authentication
Jason Terpko
 
Webinar: Building Your First App
MongoDB
 
Back to Basics: My First MongoDB Application
MongoDB
 
Search and analyze data in real time
Rohit Kalsarpe
 
Tech Talk - Blockchain presentation
Laura Steggles
 
Webinar: Was ist neu in MongoDB 2.4
MongoDB
 
MongoDB: Comparing WiredTiger In-Memory Engine to Redis
Jason Terpko
 
Webinar: Building Your First MongoDB App
MongoDB
 

What's hot (20)

PPTX
MongoDB - Sharded Cluster Tutorial
Jason Terpko
 
PDF
Working with MongoDB as MySQL DBA
Igor Donchovski
 
PPTX
Dev Jumpstart: Build Your First App with MongoDB
MongoDB
 
PDF
Maintenance for MongoDB Replica Sets
Igor Donchovski
 
PDF
Decentralized storage IPFS & Ulord
Steven Li
 
PDF
How to scale MongoDB
Igor Donchovski
 
PPTX
Dev Jumpstart: Build Your First App with MongoDB
MongoDB
 
PDF
IPFS introduction
Genta M
 
PPTX
MySQL Slow Query log Monitoring using Beats & ELK
YoungHeon (Roy) Kim
 
PPTX
Morphia, Spring Data & Co.
Tobias Trelle
 
PDF
Exploring the replication and sharding in MongoDB
Igor Donchovski
 
PDF
MongoDB HA - what can go wrong
Igor Donchovski
 
PPTX
Mongo db pefrormance optimization strategies
ronwarshawsky
 
PPTX
Back to Basics Webinar 3: Introduction to Replica Sets
MongoDB
 
PDF
Mongo db basics
Harischandra M K
 
PDF
MongodB Internals
Norberto Leite
 
PPTX
Spring Data, Jongo & Co.
Tobias Trelle
 
PDF
Enhancing the default MongoDB Security
Igor Donchovski
 
PPTX
Concurrency Patterns with MongoDB
Yann Cluchey
 
ODP
MongoDB : The Definitive Guide
Wildan Maulana
 
MongoDB - Sharded Cluster Tutorial
Jason Terpko
 
Working with MongoDB as MySQL DBA
Igor Donchovski
 
Dev Jumpstart: Build Your First App with MongoDB
MongoDB
 
Maintenance for MongoDB Replica Sets
Igor Donchovski
 
Decentralized storage IPFS & Ulord
Steven Li
 
How to scale MongoDB
Igor Donchovski
 
Dev Jumpstart: Build Your First App with MongoDB
MongoDB
 
IPFS introduction
Genta M
 
MySQL Slow Query log Monitoring using Beats & ELK
YoungHeon (Roy) Kim
 
Morphia, Spring Data & Co.
Tobias Trelle
 
Exploring the replication and sharding in MongoDB
Igor Donchovski
 
MongoDB HA - what can go wrong
Igor Donchovski
 
Mongo db pefrormance optimization strategies
ronwarshawsky
 
Back to Basics Webinar 3: Introduction to Replica Sets
MongoDB
 
Mongo db basics
Harischandra M K
 
MongodB Internals
Norberto Leite
 
Spring Data, Jongo & Co.
Tobias Trelle
 
Enhancing the default MongoDB Security
Igor Donchovski
 
Concurrency Patterns with MongoDB
Yann Cluchey
 
MongoDB : The Definitive Guide
Wildan Maulana
 
Ad

Viewers also liked (20)

PDF
How To Get Hadoop App Intelligence with Driven
Cascading
 
PPTX
Lessons about Presenting
Susan Visser
 
PDF
Internet ofthingsandbigdatawebinar
WSO2
 
PPTX
Adopting MongoDB for ADP's Next Generation Portal Platform
MongoDB
 
PDF
OPENEXPO Madrid 2015 - Advanced Applications with MongoDB
MongoDB
 
PPTX
Architecting Secure and Compliant Applications with MongoDB
MongoDB
 
PDF
Chapman: Building a High-Performance Distributed Task Service with MongoDB
MongoDB
 
PDF
MongoDB Digital Transformation 2015: DigitasLBi HELIOS
MongoDB
 
PPTX
Webinar: MongoDB and Polyglot Persistence Architecture
MongoDB
 
PPTX
Develop a Basic REST API from Scratch Using TDD with Val Karpov
MongoDB
 
POTX
Webinar: MongoDB + Hadoop
MongoDB
 
PPTX
IOT Paris Seminar 2015 - MAXXING Presentation
MongoDB
 
PPTX
Webinar: Optimize digital customer experiences with Adobe Experience Manager ...
MongoDB
 
PDF
IOT Paris Seminar 2015 - Storage Challenges in IOT
MongoDB
 
PDF
Raiding the MongoDB Toolbox with Jeremy Mikola
MongoDB
 
PPTX
Starting from Scratch with the MEAN Stack
MongoDB
 
PPTX
A Technical Introduction to WiredTiger
MongoDB
 
PDF
MongoDB and the Internet of Things
MongoDB
 
PDF
How to Boost 100x Performance for Real World Application with Apache Spark-(G...
Spark Summit
 
PPTX
IOT Seminar Paris 2015 - AXA France Presentation
MongoDB
 
How To Get Hadoop App Intelligence with Driven
Cascading
 
Lessons about Presenting
Susan Visser
 
Internet ofthingsandbigdatawebinar
WSO2
 
Adopting MongoDB for ADP's Next Generation Portal Platform
MongoDB
 
OPENEXPO Madrid 2015 - Advanced Applications with MongoDB
MongoDB
 
Architecting Secure and Compliant Applications with MongoDB
MongoDB
 
Chapman: Building a High-Performance Distributed Task Service with MongoDB
MongoDB
 
MongoDB Digital Transformation 2015: DigitasLBi HELIOS
MongoDB
 
Webinar: MongoDB and Polyglot Persistence Architecture
MongoDB
 
Develop a Basic REST API from Scratch Using TDD with Val Karpov
MongoDB
 
Webinar: MongoDB + Hadoop
MongoDB
 
IOT Paris Seminar 2015 - MAXXING Presentation
MongoDB
 
Webinar: Optimize digital customer experiences with Adobe Experience Manager ...
MongoDB
 
IOT Paris Seminar 2015 - Storage Challenges in IOT
MongoDB
 
Raiding the MongoDB Toolbox with Jeremy Mikola
MongoDB
 
Starting from Scratch with the MEAN Stack
MongoDB
 
A Technical Introduction to WiredTiger
MongoDB
 
MongoDB and the Internet of Things
MongoDB
 
How to Boost 100x Performance for Real World Application with Apache Spark-(G...
Spark Summit
 
IOT Seminar Paris 2015 - AXA France Presentation
MongoDB
 
Ad

Similar to Building Your First App with Shawn Mcarthy (20)

PPTX
Dev Jumpstart: Building Your First App
MongoDB
 
PPTX
Back to Basics, webinar 2: La tua prima applicazione MongoDB
MongoDB
 
PDF
Solving the Workflow - Building MODX.today with Gitify (2015-05-21, Alkmaar)
Mark Hamstra
 
PPTX
Dev Jumpstart: Build Your First App with MongoDB
MongoDB
 
PDF
Lean Drupal Repositories with Composer and Drush
Pantheon
 
PPTX
Back to Basics Webinar 2 - Your First MongoDB Application
Joe Drumgoole
 
PPTX
Back to Basics Webinar 2: Your First MongoDB Application
MongoDB
 
PPTX
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
MongoDB
 
PDF
오픈 소스 프로그래밍 - NoSQL with Python
Ian Choi
 
PDF
Creating a Smooth Development Workflow for High-Quality Modular Open-Source P...
Pantheon
 
PDF
Back to Basics 2017: Mí primera aplicación MongoDB
MongoDB
 
PDF
Mongo db eveningschemadesign
MongoDB APAC
 
PPTX
Android Applications Development: A Quick Start Guide
Sergii Zhuk
 
PDF
Open source projects with python
roskakori
 
PPTX
CIP Developing Curator Tool Wizards
Edwin Rojas
 
PDF
OpenERP Technical Memento
Odoo
 
PDF
22nd Athens Big Data Meetup - 1st Talk - MLOps Workshop: The Full ML Lifecycl...
Athens Big Data
 
PDF
C++ Windows Forms L01 - Intro
Mohammad Shaker
 
PPTX
Mongodb ExpressJS HandlebarsJS NodeJS FullStack
Narendranath Reddy
 
PDF
project_proposal_osrf
om1234567890
 
Dev Jumpstart: Building Your First App
MongoDB
 
Back to Basics, webinar 2: La tua prima applicazione MongoDB
MongoDB
 
Solving the Workflow - Building MODX.today with Gitify (2015-05-21, Alkmaar)
Mark Hamstra
 
Dev Jumpstart: Build Your First App with MongoDB
MongoDB
 
Lean Drupal Repositories with Composer and Drush
Pantheon
 
Back to Basics Webinar 2 - Your First MongoDB Application
Joe Drumgoole
 
Back to Basics Webinar 2: Your First MongoDB Application
MongoDB
 
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
MongoDB
 
오픈 소스 프로그래밍 - NoSQL with Python
Ian Choi
 
Creating a Smooth Development Workflow for High-Quality Modular Open-Source P...
Pantheon
 
Back to Basics 2017: Mí primera aplicación MongoDB
MongoDB
 
Mongo db eveningschemadesign
MongoDB APAC
 
Android Applications Development: A Quick Start Guide
Sergii Zhuk
 
Open source projects with python
roskakori
 
CIP Developing Curator Tool Wizards
Edwin Rojas
 
OpenERP Technical Memento
Odoo
 
22nd Athens Big Data Meetup - 1st Talk - MLOps Workshop: The Full ML Lifecycl...
Athens Big Data
 
C++ Windows Forms L01 - Intro
Mohammad Shaker
 
Mongodb ExpressJS HandlebarsJS NodeJS FullStack
Narendranath Reddy
 
project_proposal_osrf
om1234567890
 

More from MongoDB (20)

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

Recently uploaded (20)

PDF
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PDF
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
PPTX
Simple and concise overview about Quantum computing..pptx
mughal641
 
PPTX
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PPTX
IT Runs Better with ThousandEyes AI-driven Assurance
ThousandEyes
 
PDF
Get More from Fiori Automation - What’s New, What Works, and What’s Next.pdf
Precisely
 
PDF
AI-Cloud-Business-Management-Platforms-The-Key-to-Efficiency-Growth.pdf
Artjoker Software Development Company
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
PPTX
Agile Chennai 18-19 July 2025 | Emerging patterns in Agentic AI by Bharani Su...
AgileNetwork
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PDF
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
PPTX
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
PDF
Brief History of Internet - Early Days of Internet
sutharharshit158
 
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
Simple and concise overview about Quantum computing..pptx
mughal641
 
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
IT Runs Better with ThousandEyes AI-driven Assurance
ThousandEyes
 
Get More from Fiori Automation - What’s New, What Works, and What’s Next.pdf
Precisely
 
AI-Cloud-Business-Management-Platforms-The-Key-to-Efficiency-Growth.pdf
Artjoker Software Development Company
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
Agile Chennai 18-19 July 2025 | Emerging patterns in Agentic AI by Bharani Su...
AgileNetwork
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
Brief History of Internet - Early Days of Internet
sutharharshit158
 

Building Your First App with Shawn Mcarthy

  • 2. Building Your First App With MongoDB Shawn McCarthy Solutions Architect
  • 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. Shawns-MacBook-Pro:~ shawn$ tar xvf ./Downloads/mongodb-osx-x86_64-3.0.4.tgz x mongodb-osx-x86_64-3.0.4/README x mongodb-osx-x86_64-3.0.4/THIRD-PARTY-NOTICES x mongodb-osx-x86_64-3.0.4/GNU-AGPL-3.0 x mongodb-osx-x86_64-3.0.4/bin/mongodump x mongodb-osx-x86_64-3.0.4/bin/mongorestore x mongodb-osx-x86_64-3.0.4/bin/mongoexport x mongodb-osx-x86_64-3.0.4/bin/mongoimport x mongodb-osx-x86_64-3.0.4/bin/mongostat x mongodb-osx-x86_64-3.0.4/bin/mongotop x mongodb-osx-x86_64-3.0.4/bin/bsondump x mongodb-osx-x86_64-3.0.4/bin/mongofiles x mongodb-osx-x86_64-3.0.4/bin/mongooplog x mongodb-osx-x86_64-3.0.4/bin/mongoperf x mongodb-osx-x86_64-3.0.4/bin/mongosniff x mongodb-osx-x86_64-3.0.4/bin/mongod x mongodb-osx-x86_64-3.0.4/bin/mongos x mongodb-osx-x86_64-3.0.4/bin/mongo Unpacking the Tarball
  • 13. $ cd mongodb-osx-x86_64-3.0.3/bin $ sudo mkdir –p /data/db $ sudo chown -R shawn:staff /data $ ./mongod Running MongoDB
  • 14. Shawns-MacBook-Pro:bin shawn$ ./mongod 2015-07-18T18:36:48.814-0400 I JOURNAL [initandlisten] journal dir=/data/db/journal 2015-07-18T18:36:48.815-0400 I JOURNAL [initandlisten] recover : no journal files present, no recovery needed 2015-07-18T18:36:48.836-0400 I JOURNAL [durability] Durability thread started 2015-07-18T18:36:48.836-0400 I JOURNAL [journal writer] Journal writer thread started 2015-07-18T18:36:48.837-0400 I CONTROL [initandlisten] MongoDB starting : pid=27923 port=27017 dbpath=/data/db 64- bit host=Shawns-MacBook-Pro.local 2015-07-18T18:36:48.837-0400 I CONTROL [initandlisten] 2015-07-18T18:36:48.837-0400 I CONTROL [initandlisten] ** WARNING: soft rlimits too low. Number of files is 256, should be at least 1000 2015-07-18T18:36:48.837-0400 I CONTROL [initandlisten] db version v3.0.4 2015-07-18T18:36:48.837-0400 I CONTROL [initandlisten] git version: 0481c958daeb2969800511e7475dc66986fa9ed5 2015-07-18T18:36:48.837-0400 I CONTROL [initandlisten] build info: Darwin mci-osx108-11.build.10gen.cc 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-07-18T18:36:48.837-0400 I CONTROL [initandlisten] allocator: system 2015-07-18T18:36:48.837-0400 I CONTROL [initandlisten] options: {} 2015-07-18T18:36:48.842-0400 I INDEX [initandlisten] allocating new ns file /data/db/local.ns, filling with zeroes... 2015-07-18T18:36:48.899-0400 I STORAGE [FileAllocator] allocating new datafile /data/db/local.0, filling with zeroes... 2015-07-18T18:36:48.899-0400 I STORAGE [FileAllocator] creating directory /data/db/_tmp 2015-07-18T18:36:49.070-0400 I STORAGE [FileAllocator] done allocating datafile /data/db/local.0, size: 64MB, took 0.17 secs 2015-07-18T18:36:49.196-0400 I NETWORK [initandlisten] waiting for connections on port 27017 Log Output from mongod
  • 15. Shawns-MacBook-Pro:bin shawn$ ./mongo MongoDB shell version: 3.0.4 connecting to: 127.0.0.1:7=27017/test > db.names.insert({'fullname':’Shawn McCarthy’}) WriteResult({ "nInserted" : 1 }) > db.names.findOne() { "_id" : ObjectId("55aad5d2795e9e59af9b375d"), "fullname" : ”Shawn McCarthy", } > 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 bottle 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 Import the modules needed for Pymongo and the bottle web framework Connect to the MongoDB Database on Localhost and use the “test” database 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 Start the webserver on locahost, listening on port 8080
  • 21. Determine Your Entities First Step In Your App
  • 22. 22 Entities in our Blogging System • Users (post authors) • Posts • Comments • Tags
  • 23. We Would Start By Doing Schema Design In a relational based app
  • 25. In MongoDB We Start By Building Our App And Let The Schema Evolve
  • 26. 26 MongoDB ERD title body date username Posts [ ] comments [ ] tags Username password email Users
  • 28. user = { _id: ’mccarthy', password: ‘XXXXX’, email: ’[email protected]’ } Start with an object (or array, hash, dict, etc)
  • 29. > db.users.insert(user) Insert the record No collection creation needed
  • 30. > db.users.findOne() { "_id" : ”mccarthy", "password" : ”XXXXX", "email" : “[email protected]” } Querying for the user
  • 31. > db.posts.insert({ title: ‘Hello World’, body: ‘This is my first blog post’, date: new Date(‘2013-06-20’), username: ‘mccarthy’, tags: [‘adventure’, ‘mongodb’], comments: [] }) Creating a blog post
  • 32.  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" : ”mccarthy", "tags" : [ "adventure", "mongodb" ], "comments" : [ ] } Finding the Post
  • 33. > 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" : ”mccarthy", "tags" : [ "adventure", "mongodb" ], "comments" : [ ] } Querying an Array
  • 34. > db.posts.update( {_id: new ObjectId("51c3bcddfbd5d7261b4cdb5b")}, {$push:{comments: {name: 'Steve Blank', comment: 'Awesome Post'}}}) Using Update to Add a Comment Predicate of the query. Specifies which document to update “push” a new document under the “comments” array
  • 35. > 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" : ”mccarthy" } Post with Comment Attached
  • 37. 37

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.
  • #22: Ok, the first step in building an application to manage this library is to think about what entities we need to model and maintain.
  • #23: 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.
  • #24: In a relational based solution, we would probably start by doing schema design. We would build out an ERD diagram.
  • #25: 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.
  • #26: 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.
  • #27: 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.
  • #28: Now I would like to turn to working within data within mongodb for blog application.
  • #29: 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.
  • #30: 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.
  • #31: 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.
  • #32: 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.
  • #33: 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.
  • #34: 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”
  • #35: 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.
  • #36: 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.
  • #37: 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.
  • #38: There are drivers that are created and maintained by 10gen for most popular languages. You can find them at api.mongodb.org.
  • #39: 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.
  • #40: 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.