dev jumpstart: build your first app with mongodb

Post on 07-Jul-2015

769 Views

Category:

Technology

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

MongoDB SF 2014

TRANSCRIPT

Building Your First App With

MongoDB

Andrew Erlichson,

Vice President of Engineering

Developer Experience

What is MongoDB

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

Terminology

RDBMS MongoDB

Table, View ➜ Collection

Row ➜ Document

Index ➜ Index

Join ➜ Embedded Document

Foreign Key ➜ Reference

Partition ➜ Shard

Open Source

• MongoDB is an open source project

• On GitHub

• Licensed under the AGPL

• Started & sponsored by MongoDB, Inc.

• Commercial licenses available

• Contributions welcome

Horizontally Scalable

Database Landscape

Full Featured

• Ad Hoc queries

• Real time aggregation

• Rich query capabilities

• Strongly consistent

• Geospatial features

• Support for most programming languages

• Flexible schema

http://www.mongodb.org/downloads

$ tar xvf mongodb-osx-x86_64-2.6.5.tgz

$ cd mongodb-osx-x86_64-2.6.5/bin

$ mkdir –p /data/db

$ ./mongod

Running MongoDB

Andrews-Air:MongoDB-SF2014 aje$ mongo

MongoDB shell version: 2.6.5

connecting to: test

Server has startup warnings:

2014-12-01T23:29:15.317-0500 [initandlisten]

2014-12-01T23:29:15.317-0500 [initandlisten] ** WARNING: soft rlimits too low. Number of files is 256, should be at least 1000

aje_air:PRIMARY> db.names.insert({'fullname':'Andrew Erlichson'});

WriteResult({ "nInserted" : 1 })

aje_air:PRIMARY> db.names.findOne();

{

"_id" : ObjectId("547dd9a0f907ebca54d1d994"),

"fullname" : "Andrew Erlichson"

}

aje_air:PRIMARY>

Mongo Shell

Web Demo

• MongoDB

• Python

• Bottle web framework

• Pymongo

from pymongo import MongoClientfrom bottle import route, run, template

@route('/')

def index():

collection = db.namesdoc = 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.namesdoc = 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 MongoClientfrom bottle import route, run, template

@route('/')

def index():

collection = db.namesdoc = collection.find_one()return "Hello " + doc['fullname']

run(host='localhost', port=8080)

hello.py

Connect to the MongoDBDatabase on Localhost and

use the “test” database

from pymongo import MongoClientfrom bottle import route, run, template

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 MongoClientfrom bottle import route, run, template

@route('/')

def index():

collection = db.namesdoc = 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

Let’s Build a Blog

Determine Your Entities

First Step In Your App

Entities in our Blogging System

• Users (post authors)

• Posts

• Comments

• Tags

We Would Start By Doing Schema

Design

In a relational based app

Typical (relational) ERD

tag_idtag

tags

post_idpost_titlebodypost_datepost_author_uid

post_idcomment_idcommentauthor_namecomment_dateauthor_email

uidusernamepasswordEmail

post_idtag_id

users

posts comments

post_tags

We Start By Building Our App

And Let The Schema Evolve

MongoDB ERD

titlebodydateusername

Posts

[ ] comments

[ ] tags

Usernamepasswordemail

Users

Working in The Shell

user = {

_id: ’erlichson',

"password" : "a7cf1c46861b140894e1371a0eb6cd6791ca2e339f1a8d83a1846f6c81141dec,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

Completed Blog Demo

• Python

• Bottle.py

• Pymongo

• Features Supported

– Creating users

– Logging in

– Logging out

– Displaying Content

– Adding a new Blog Post

MongoDB Drivers

http://docs.mongodb.org/ecosystem/drivers/

Next Steps

http://docs.mongodb.org/manual/

MongoDB University

Data Modeling Deep Dive

2pm in Robertson Auditorium 1

Replication Internals

2pm in Fischer Banquet Room West

MongoDB Performance Debugging

11:40am in Robertson Auditorium 3

How to Achieve Scale

11:40am in Robertson Auditorium 2

top related