48

Dev Jumpstart: Building Your First App

  • Upload
    mongodb

  • View
    185

  • Download
    0

Embed Size (px)

Citation preview

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 MongoDBTable, View ➜ CollectionRow ➜ DocumentIndex ➜ IndexJoin ➜ Embedded DocumentForeign Key ➜ ReferencePartition ➜ 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.tgzx mongodb-osx-x86_64-3.0.3/READMEx mongodb-osx-x86_64-3.0.3/THIRD-PARTY-NOTICESx mongodb-osx-x86_64-3.0.3/GNU-AGPL-3.0x mongodb-osx-x86_64-3.0.3/bin/mongodumpx mongodb-osx-x86_64-3.0.3/bin/mongorestorex mongodb-osx-x86_64-3.0.3/bin/mongoexportx mongodb-osx-x86_64-3.0.3/bin/mongoimportx mongodb-osx-x86_64-3.0.3/bin/mongostatx mongodb-osx-x86_64-3.0.3/bin/mongotopx mongodb-osx-x86_64-3.0.3/bin/bsondumpx mongodb-osx-x86_64-3.0.3/bin/mongofilesx mongodb-osx-x86_64-3.0.3/bin/mongooplogx mongodb-osx-x86_64-3.0.3/bin/mongoperfx mongodb-osx-x86_64-3.0.3/bin/mongosniffx mongodb-osx-x86_64-3.0.3/bin/mongodx mongodb-osx-x86_64-3.0.3/bin/mongosx 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 MongoClientfrom 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

from pymongo import MongoClientfrom 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

from pymongo import MongoClientfrom 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

Connect to the MongoDB Database on Localhost and use the “test” database

from pymongo import MongoClientfrom 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 MongoClientfrom 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

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_idtag

tags

post_idpost_titlebodypost_datepost_author_uid

post_idcomment_idcommentauthor_namecomment_dateauthor_email

uidusernamepasswordEmail

post_idtag_id

users

posts comments

post_tags

In MongoDB We Start By Building Our App

And Let The Schema Evolve

30

MongoDB ERD

titlebodydateusername

Posts

[ ] comments

[ ] tags

Usernamepasswordemail

Users

Manipulating Blog Data

(mongo shell version)

user = {

_id: ’erlichson',

"password" : "a7cf1c46861b140894e1371a0eb6cd6791ca2e339f1a8d83a1846f6c81141dec,zYJue",

,

email: ’[email protected]',

}

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" : “[email protected]

}

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

> 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

> 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

Next Steps

46

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