SlideShare a Scribd company logo
MongoDB and PHP
My name is
Steve Francia

     @spf13
• 15+ years building the
  internet

• Father, husband,
  skateboarder

• Chief Solutions Architect @
  10gen

• Author of upcoming O’Reilly
  publication “PHP and
  MongoDB”
Introduction to
   MongoDB
Why MongoDB?
MongoDB Goals
• OpenSource
• Designed for today
 • Today’s hardware / environments
 • Today’s challenges
• Easy development
• Reliable
• Scalable
• Company behind MongoDB
 • AGPL license, own copyrights, engineering
    team
  • support, consulting, commercial license
    revenue
• Management
 • Google/DoubleClick, Oracle, Apple, NetApp
 • Funding: Sequoia, Union Square, Flybridge
 • Offices in NYC, Redwood Shores & London
 • 60+ employees
A bit of history
1974
The relational database is created
MongoDB and PHP ZendCon 2011
MongoDB and PHP ZendCon 2011
1979
1979   1982-1996
1979   1982-1996   1995
Computers in 1995

•Pentium 100 mhz
•10base T
•16 MB ram
•200 MB HD
Cell Phones in 2011

•Dual core 1.5 Ghz
•WiFi 802.11n (300+ Mbps)
•1 GB ram
•64GB Solid State
How about a DB
designed for today?
It started with
  DoubleClick
Signs something
       needed
•doubleclick - 400,000 ads/second
•caching is de rigueur
•complex ORM frameworks
•computer architecture increasing in
  complexity
•cloud computing
Requirements
  We need enough functionality to handle
  broad set of use cases


•strong consistency / atomicity
•secondary indexes
•ad hoc queries
Trim unneeded
         features
  Leave out a few things so we can scale


•no choice but to leave out relational
•distributed transactions are hard to
  scale
Needed a scalable
      data model
  Considered....


•key/value
•columnar / tabular
•document oriented (JSON inspired)
MongoDB philosphy
• Keep functionality when we can (key/
  value stores are great, but we need more)
• Non-relational (no joins) makes scaling
  horizontally practical
• Document data models are good
• Database technology should run
  anywhere VMs, cloud or straight metal
MongoDB is:
          Application      Document
                           Oriented
                           { author: “steve”,
    High                     date: new Date(),
                             text: “About MongoDB...”,
Performance                  tags: [“tech”, “database”]}




                             Fully
                           Consistent

   Horizontally Scalable
MongoDB

•JSON Documents
•Querying/Indexing/Updating similar to
  relational databases
•Traditional Consistency
•Auto-Sharding
Under the hood

•Written in C++
•Available on most platforms
•Data serialized to BSON
•Extensive use of memory-mapped files
Database Landscape
This has led
    some to say

“
MongoDB has the best
features of key/ values
stores, document databases
and relational databases in
one.
               John Nunemaker
Use Cases
CMS / Blog
Needs:
• Business needed modern data store for rapid development and
  scale

Solution:
• Use PHP & MongoDB

Results:
• Real time statistics
• All data, images, etc stored together, easy access, easy
  deployment, easy high availability
• No need for complex migrations
• Enabled very rapid development and growth
Photo Meta-Data
Problem:
• Business needed more flexibility than Oracle could deliver

Solution:
• Use MongoDB instead of Oracle

Results:
• Developed application in one sprint cycle
• 500% cost reduction compared to Oracle
• 900% performance improvement compared to Oracle
Customer Analytics
Problem:
• Deal with massive data volume across all customer sites

Solution:
• Use MongoDB to replace Google Analytics / Omniture options

Results:
• Less than one week to build prototype and prove business case
• Rapid deployment of new features
Online Dictionary
Problem:
• MySQL could not scale to handle their 5B+ documents

Solution:
• Switched from MySQL to MongoDB

Results:
• Massive simplification of code base
• Eliminated need for external caching system
• 20x performance improvement over MySQL
E-commerce
Problem:
• Multi-vertical E-commerce impossible to model (efficiently) in
  RDBMS

Solution:
• Switched from MySQL to MongoDB

Results:
•   Massive simplification of code base
•   Rapidly build, halving time to market (and cost)
•   Eliminated need for external caching system
•   50x+ improvement over MySQL
Tons more
Pretty much if you can use a RDMBS or Key/Value
             MongoDB is a great fit
In Good Company
MongoDB in PHP
Relational made normalized
     data look like this
Document databases make
normalized data look like this
Terminology
   RDBMS                    Mongo
Table, View     ➜   Collection
Row             ➜   JSON Document
Index           ➜   Index
Join            ➜   Embedded Document
Partition       ➜   Shard
Partition Key   ➜   Shard Key
Documents to Objects
Documents to Arrays
 Tables to Documents
           {
           PostObject Object(
               [title] => MongoDB
              title: ‘MongoDB’,
               [contributors] => Array(
              contributors: [
                   [0] => PersonObject Object(
                 { name: ‘Eliot Horowitz’,
                       [name] => Eliot Horowitz
                       [email] => eh@10gen.com
                   email: ‘eh@10gen.com’ },
                   )
                 { name: PersonObjectMerriman’,
                   [1] => ‘Dwight      Object(
                   email: ‘dm@10gen.com’ }
                       [name] => Dwight Merriman
                       [email] => dm@10gen.com
              ],
                   )
              model: {
               )
                  relational: false,
               [model] => ModelObject Object(
                  [relational] =>
                  awesome:=>true
                  [awesome]    1
              })
           )
           }
Documents to Objects
    Documents to Arrays
     Tables to Documents
{                                   array(
                                    PostObject Object(
    title: ‘MongoDB’,                 "title" =>=> MongoDB
                                        [title] 'MongoDB',
                                      "contributors" =>=> Array(
                                        [contributors] array(
    contributors: [                      array( => PersonObject Object(
                                            [0]
       { name: ‘Eliot Horowitz’,           'name' => 'Eliot Horowitz',
                                                [name] => Eliot Horowitz
         email: ‘eh@10gen.com’ },          'email' => 'eh@10gen.com'
                                                [email] => eh@10gen.com
                                         ), )
       { name: ‘Dwight Merriman’,        array( => PersonObject Object(
                                            [1]
         email: ‘dm@10gen.com’ }           'name' => 'Dwight Merriman',
                                                [name] => Dwight Merriman
                                           'email' => 'dm@10gen.com'
                                                [email] => dm@10gen.com
    ],
                                         ) )
    model: {                          ),)
        relational: false,            "model" =>=> ModelObject Object(
                                        [model] array(
                                           'relational' => false,
                                           [relational]
        awesome: true                      'awesome' => true
                                           [awesome]    1
    }                                 ) )
}                                   )
Documents to Objects
    Documents to Arrays
     Tables to Documents
{                                   array(
                                    PostObject Object(
    title: ‘MongoDB’,                 "title" =>=> MongoDB
                                        [title] 'MongoDB',
                                      "contributors" =>=> Array(
                                        [contributors] array(
    contributors: [                      array( => PersonObject Object(
                                            [0]
       { name: ‘Eliot Horowitz’,           'name' => 'Eliot Horowitz',
                                                [name] => Eliot Horowitz
         email: ‘eh@10gen.com’ },          'email' => 'eh@10gen.com'
                                                [email] => eh@10gen.com
                                         ), )
       { name: ‘Dwight Merriman’,        array( => PersonObject Object(
                                            [1]
         email: ‘dm@10gen.com’ }           'name' => 'Dwight Merriman',
                                                [name] => Dwight Merriman
                                           'email' => 'dm@10gen.com'
                                                [email] => dm@10gen.com
    ],
                                         ) )
    model: {                          ),)
        relational: false,            "model" =>=> ModelObject Object(
                                        [model] array(
                                           'relational' => false,
                                           [relational]
        awesome: true                      'awesome' => true
                                           [awesome]    1
    }                                 ) )
}                                   )
MongoDB speaks
     PHP
This has led
    some to say


“
The single best interface
(API) of any php
extension.  
       Matthew Weier O'Phinney
PHP Driver
Installing the driver

 $ pecl install mongo




Add to php.ini

 extension = mongo.so
Connecting to the DB

$connection = new Mongo();

$db = $connection->selectDB('blog');

$posts = $db->post;




If the DB or collection doesn’t exist,
mongoDB will create it on connect.
Documents
Blog Post Document

$p1 = array("author"   =>   "roger",
            "date"     =>   new MongoDate(),
            "text"     =>   "about mongoDB...",
            "tags"     =>   array('tech', 'databases')
            );

$posts->save($p1);
Querying
print_r($posts->findOne());
> db.posts.findOne()
Array(
    [_id] => MongoId Object(
>   { _id : ObjectId("4c4ba5c0672c685e5e8aabf3"),
            [$id] => 4e9796764a18173a17000000
    author : "roger",
        )
      date : "Sat Jul 24 2010 19:47:11",
    [author] => roger
      text : "About MongoDB...",
    [date] => MongoDate Object(
      tags : [ "tech", "databases" ] }
            [sec] => 1318557302
            [usec] => 581000
        )
    [text] => about mongoDB...
    [tags] => Array(
 Note: _id is unique, but can be anything
            [0] => tech
            [1] => databases
you’d like
        )
)
Querying
print_r($posts->findOne());
> db.posts.findOne()
Array(
    [_id] => MongoId Object(
>   { _id : ObjectId("4c4ba5c0672c685e5e8aabf3"),
            [$id] => 4e9796764a18173a17000000
    author : "roger",
        )
      date : "Sat Jul 24 2010 19:47:11",
    [author] => roger
      text : "About MongoDB...",
    [date] => MongoDate Object(
      tags : [ "tech", "databases" ] }
            [sec] => 1318557302
            [usec] => 581000
        )
    [text] => about mongoDB...
    [tags] => Array(
 Note: _id is unique, but can be anything
            [0] => tech
            [1] => databases
you’d like
        )
)
Inserting Objects
class PostObj {
    public $comments = array();
    public function __construct($author, $title, $content)
{
        $this->author = $author;
        $this->title = $title;
        $this->content = $content;
    }
}

$posts->insert(new PostObj("Steve",
                           "My first blog post",
                           "Hello, World!"));
MongoId
An autogenerated primary key

$x = array("foo" => 1, "bar" => 2);
$db->baz->save($x);
var_dump($x['_id']);

Result:

object(MongoId)#4 (1) {
  ["$id"]=> string(24) "4e9cc76a4a1817fd21000000"
}
MongoId
An autogenerated primary key


object(MongoId)#4 (1) {
  ["$id"]=> string(24) "4e9cc76a4a1817fd21000000"
}

                4e9cc76a4a1817fd21000000
                |------||----||--||----|
                   ts     mac pid inc
Update Operations
 $set, $unset, $inc, $push, $pushAll,
 $pull, $pullAll, $bit

$change = array('$push' =>
            array('comments' =>
                array(
                    'author' => 'Fred',
                    'created' => new MongoDate(),
                    'comment' => 'Best post ever!.'
                )
            )
        );

$posts->update(array("_id" => $id), $change);
Nested Documents
Array(
    {   _id : ObjectId("4c4ba5c0672c685e5e8aabf3"),
    [_id] => MongoId Object (
            [$id] => 4e9796764a18173a17000000
    )   author : "roger",
    [author] => roger
        date : "Sat Apr 24 2011 19:47:11",
    [comments] => Array(

        text : "About MongoDB...",
        [0] => Array(
             [author] => Fred
        tags : [ "tech", "databases" ],
             [created] => MongoDate Object(
                     [sec] => 1318899392
        comments : [ [usec] => 176000
                 )
	              {
             [comment] => Dumb post.
         )
	   )          	 author : "Fred",
               	
    [date] => MongoDate Object(
	              	 date : "Sat Apr 25 2010 20:51:03 GMT-0700",
               	
        [sec] => 1318557302
        [usec] => 581000
	   )          	 text : "Best Post Ever!"
               	
    [tags] => Array(
	              	
               }
        [0] => tech

    )
         ]
        [1] => databases


}
)
    [text] => about mongoDB...
Nested Documents
Array(
    {   _id : ObjectId("4c4ba5c0672c685e5e8aabf3"),
    [_id] => MongoId Object (
            [$id] => 4e9796764a18173a17000000
    )   author : "roger",
    [author] => roger
        date : "Sat Apr 24 2011 19:47:11",
    [comments] => Array(

        text : "About MongoDB...",
        [0] => Array(
             [author] => Fred
        tags : [ "tech", "databases" ],
             [created] => MongoDate Object(
                     [sec] => 1318899392
        comments : [ [usec] => 176000
                 )
	              {
             [comment] => Dumb post.
         )
	   )          	 author : "Fred",
               	
    [date] => MongoDate Object(
	              	 date : "Sat Apr 25 2010 20:51:03 GMT-0700",
               	
        [sec] => 1318557302
        [usec] => 581000
	   )          	 text : "Best Post Ever!"
               	
    [tags] => Array(
	              	
               }
        [0] => tech

    )
         ]
        [1] => databases


}
)
    [text] => about mongoDB...
Querying

$posts = $blog->find(array(
     "author" => "Roger"));

$commentsByFred = $blog->find(array(
     "comments.author" => "Fred"));

$commentsByFred = $blog->find(array(
     "comments.author" =>
     new MongoRegex("/fred/i")));
It’s all about the $
 $ instead of >, <, =, etc.

 $gt, $gte, $lt, $lte, $eq, $neq, $exists,
 $set, $mod, $where, $in, $nin, $inc
 $push, $pull, $pop, $pushAll, $popAll

$c->find(array("x" => array('$gt' => 4)));

$c->find(array("x" => array(“$gt” => 4)));
It’s all about the $
 $ instead of >, <, =, etc.

 $gt, $gte, $lt, $lte, $eq, $neq, $exists,
 $set, $mod, $where, $in, $nin, $inc
 $push, $pull, $pop, $pushAll, $popAll

$c->find(array("x" => array('$gt' => 4)));

$c->find(array("x" => array(“$gt” => 4)));
Adjust the behavior
           in php.ini or using ini_set()


php.ini
---------------
mongo.cmd = ":"

$c->find(array("x" => array(':gt' => 4)));

     or

ini_set("mongo.cmd", ".");
$c->find(array("x" => array('.gt' => 4)));
Indexing
 including secondary and compound
 indexes

$people->ensureIndex(array("age" => 1));

$people->ensureIndex(array(
    "name" => -1,
    "ts" => -1,
    "comments.author" => 1
));
More Indexing
// Index nested documents
$posts->ensureIndex( array("comments.author" => 1) )
$posts->find( array("comments.author" => "Fred") )

// Index on tags (multi-key index)
$posts->ensureIndex( array("tags" => 1 ) )
$posts->find( array("tags" => "tech") )

// geospatial index
$posts->ensureIndex( array("author.location" => "2d") )
$posts->find( array("author.location" =>
                array( '$near' => array(22,42)));
Cursors

$cursor = $c->find(array("foo" => "bar"))

foreach ($cursor as $id => $value) {
    echo "$id: ";
    var_dump( $value );
}

$a = iterator_to_array($cursor);
Paging

$page_num = 3;
$results_per_page = 10;

$cursor = $results->find()
    ->sort(array("ts" => -1))
    ->skip($page_num * $results_per_page)
    ->limit($results_per_page);
Rich Documents
{   _id : ObjectId("4c4ba5c0672c685e5e8aabf3"),

    line_items : [ { sku: ‘tt-123’,
                     name: ‘Coltrane: Impressions’ },
                   { sku: ‘tt-457’,
                     name: ‘Davis: Kind of Blue’ } ],

    address : { name: ‘Banker’,
                street: ‘111 Main’,
                zip: 10010 },

    payment: { cc: 4567,
               exp: Date(2011, 7, 7) },

    subtotal: 2355
}
Grid FS
Storing Files




Under 16mb
Storing Big Files




>16mb stored in 16mb chunks
Storing Big Files




Works with replicated
and sharded systems
A better network FS
• GridFS files are seamlessly sharded & replicated.
• No OS constraints...
 • No file size limits
 • No naming constraints
 • No folder limits
 • Standard across different OSs
• MongoDB automatically generate the MD5 hash
  of the file
Storing Files
$grid = $db->getGridFS();

// The file's location in the File System
$path = "/tmp/";
$filename = "movie.mp4";

// Note metadata field & filename field
$storedfile = $grid->storeFile($path . $filename,
array("metadata" => array("filename" => $filename),
"filename" => $filename));

// Return newly stored file's Document ID
echo $storedfile;
Storing Data

$grid = $db->getGridFS();
$filename = "zelda.jpg";
$storedfile = $grid->storeBytes("ÿØÿÉ
€ ^@^PJFIF^@^A^A^A,^G^E^E^G,...",
                 array("metadata" => array("filename" =>
$filename),
                 "filename" => $filename));
Streaming Data
$gridFS = $db->getGridFS();

// Find image to stream
$image = $gridFS->findOne("zelda.jpg");

// Stream image to browser
header('Content-type: image/jpeg');
echo $image->getBytes();
PHP Libraries for
   MongoDB
Libraries & Frameworks
• Doctrine MongoDB ODM   • Zend Framework
• Active Mongo           • Lithium
• Mongo Queue            • Symfony2
• Morph                  • Fuel
• Mandango               • Fat Free Framework
Doctrine MongoDB ODM
• Provides full validation
• Seamless integration with Doctrine ORM
   • Useful for hybrid solutions
• Follows same persistence model as Doctrine
• Uses a Document Manager & annotations
• Supports embedded and referenced objects
• Can use mongo’s query interface
• Supports in place updates
     https://github.com/doctrine/mongodb-odm
Mandango
•Very light and fast
•Event support
•Supports embedded and referenced
  objects
•uses the mongo query syntax
•Lacking validation, but events can be
  utilized to validate
    https://github.com/mandango/mandango
Active Mongo
•Uses ActiveRecord (active document)
  interface
•Supports full validation
•Supports in place updating
•Uses native query interface
•Supports referenced documents
      https://github.com/crodas/ActiveMongo
Morph

•Follows the Active Record model
•Has own query object (Morph_Query)
•Doesn’t provide validation
•Doesn’t support embedded or referenced
  objects.

   https://github.com/a-musing-moose/morph
Mongo Queue
  An extensible job/message queueing system that
  uses mongodb as the persistent storage engine.


• Fully Configurable
• Distributed
• Atomic Locking
• Priority Support
• Worker Timeout Support
• Stable
         https://github.com/skiz/mongo_queue
http://spf13.com
                                http://github.com/spf13
                                @spf13




           Questions?
        download at mongodb.org
PS: We’re hiring!! Contact us at jobs@10gen.com
MongoDB and PHP ZendCon 2011

More Related Content

KEY
MongoDB, PHP and the cloud - php cloud summit 2011
PPTX
DOM and Events
PDF
Di web tech mail (no subject)
PDF
Storing tree structures with MongoDB
KEY
Practical Ruby Projects with MongoDB - MongoSF
KEY
Practical Ruby Projects (Alex Sharp)
PPT
03DOM.ppt
PPT
MongoDB, PHP and the cloud - php cloud summit 2011
DOM and Events
Di web tech mail (no subject)
Storing tree structures with MongoDB
Practical Ruby Projects with MongoDB - MongoSF
Practical Ruby Projects (Alex Sharp)
03DOM.ppt

What's hot (19)

PPTX
MongoDB Schema Design: Four Real-World Examples
PDF
MongoDB and Ruby on Rails
KEY
Introduction to Restkit
PDF
Couchbase Korea User Group 2nd Meetup #2
PDF
Ext GWT 3.0 Data Widgets
PDF
Data formats
PDF
Improving RDF Search Performance with Lucene and SIREN
PDF
Paintfree Object-Document Mapping for MongoDB by Philipp Krenn
PPTX
Dev Jumpstart: Schema Design Best Practices
PPTX
Advanced Document Modeling Techniques from a High-Scale Commerce Platform
KEY
Schema Design (Mongo Austin)
PPT
J query introduction
PDF
Building DSLs with Groovy
PPTX
How to win friends and influence people (with Hadoop)
PDF
Learn css3
PDF
Json tutorial, a beguiner guide
PPTX
Cordova training : Day 4 - Advanced Javascript
PPTX
MongoDB + Java - Everything you need to know
PDF
jQuery Rescue Adventure
MongoDB Schema Design: Four Real-World Examples
MongoDB and Ruby on Rails
Introduction to Restkit
Couchbase Korea User Group 2nd Meetup #2
Ext GWT 3.0 Data Widgets
Data formats
Improving RDF Search Performance with Lucene and SIREN
Paintfree Object-Document Mapping for MongoDB by Philipp Krenn
Dev Jumpstart: Schema Design Best Practices
Advanced Document Modeling Techniques from a High-Scale Commerce Platform
Schema Design (Mongo Austin)
J query introduction
Building DSLs with Groovy
How to win friends and influence people (with Hadoop)
Learn css3
Json tutorial, a beguiner guide
Cordova training : Day 4 - Advanced Javascript
MongoDB + Java - Everything you need to know
jQuery Rescue Adventure
Ad

Viewers also liked (13)

PPTX
Simulation d'un réseau BSS dans la commune d'arrondissement de Douala 5e
PPTX
PDF
Programmation orientée objet en PHP 5
PDF
83839589 radius
PDF
Wi fi-radius
PDF
Un exemple élémentaire d'application MVC en PHP
PPTX
Mise en place d’un serveur radius
PDF
Symfony2 Presentation
ODP
Formation PHP avancé - Cake PHP
PDF
Free radius
DOCX
Mini projet individuel php
PDF
Rapport sécurité
Simulation d'un réseau BSS dans la commune d'arrondissement de Douala 5e
Programmation orientée objet en PHP 5
83839589 radius
Wi fi-radius
Un exemple élémentaire d'application MVC en PHP
Mise en place d’un serveur radius
Symfony2 Presentation
Formation PHP avancé - Cake PHP
Free radius
Mini projet individuel php
Rapport sécurité
Ad

Similar to MongoDB and PHP ZendCon 2011 (20)

PDF
MongoDB and Schema Design
PDF
The Fine Art of Schema Design in MongoDB: Dos and Don'ts
KEY
mongoDB at Visibiz
PDF
MongoDB in FS
PDF
2013-03-23 - NoSQL Spartakiade
PDF
MongoDB Schema Design (Event: An Evening with MongoDB Houston 3/11/15)
PDF
2012-08-29 - NoSQL Bootcamp (Redis, RavenDB & MongoDB für .NET Entwickler)
PPT
Building Your First MongoDB App ~ Metadata Catalog
PPTX
Schema design mongo_boston
PDF
Schema Design
KEY
NOSQL101, Or: How I Learned To Stop Worrying And Love The Mongo!
PDF
Schema & Design
PDF
Doctrine MongoDB ODM (PDXPHP)
PDF
Transition from relational to NoSQL Philly DAMA Day
PDF
Navigating the Transition from relational to NoSQL - CloudCon Expo 2012
PPTX
Conceptos básicos. seminario web 3 : Diseño de esquema pensado para documentos
PDF
Building your first app with MongoDB
PPTX
MongoDB Workshop.pptx computer science and engineering
PPTX
Mongodb introduction and_internal(simple)
PPTX
Schema Design
MongoDB and Schema Design
The Fine Art of Schema Design in MongoDB: Dos and Don'ts
mongoDB at Visibiz
MongoDB in FS
2013-03-23 - NoSQL Spartakiade
MongoDB Schema Design (Event: An Evening with MongoDB Houston 3/11/15)
2012-08-29 - NoSQL Bootcamp (Redis, RavenDB & MongoDB für .NET Entwickler)
Building Your First MongoDB App ~ Metadata Catalog
Schema design mongo_boston
Schema Design
NOSQL101, Or: How I Learned To Stop Worrying And Love The Mongo!
Schema & Design
Doctrine MongoDB ODM (PDXPHP)
Transition from relational to NoSQL Philly DAMA Day
Navigating the Transition from relational to NoSQL - CloudCon Expo 2012
Conceptos básicos. seminario web 3 : Diseño de esquema pensado para documentos
Building your first app with MongoDB
MongoDB Workshop.pptx computer science and engineering
Mongodb introduction and_internal(simple)
Schema Design

More from Steven Francia (20)

PDF
State of the Gopher Nation - Golang - August 2017
PDF
Building Awesome CLI apps in Go
PDF
The Future of the Operating System - Keynote LinuxCon 2015
PDF
7 Common Mistakes in Go (2015)
PDF
What every successful open source project needs
PDF
7 Common mistakes in Go and when to avoid them
PDF
Go for Object Oriented Programmers or Object Oriented Programming without Obj...
PDF
Painless Data Storage with MongoDB & Go
PDF
Getting Started with Go
PDF
Build your first MongoDB App in Ruby @ StrangeLoop 2013
PDF
Modern Database Systems (for Genealogy)
PPTX
Introduction to MongoDB and Hadoop
PPTX
Future of data
PDF
MongoDB, Hadoop and humongous data - MongoSV 2012
KEY
Big data for the rest of us
KEY
OSCON 2012 MongoDB Tutorial
KEY
Replication, Durability, and Disaster Recovery
KEY
Multi Data Center Strategies
KEY
NoSQL databases and managing big data
KEY
MongoDB, Hadoop and Humongous Data
State of the Gopher Nation - Golang - August 2017
Building Awesome CLI apps in Go
The Future of the Operating System - Keynote LinuxCon 2015
7 Common Mistakes in Go (2015)
What every successful open source project needs
7 Common mistakes in Go and when to avoid them
Go for Object Oriented Programmers or Object Oriented Programming without Obj...
Painless Data Storage with MongoDB & Go
Getting Started with Go
Build your first MongoDB App in Ruby @ StrangeLoop 2013
Modern Database Systems (for Genealogy)
Introduction to MongoDB and Hadoop
Future of data
MongoDB, Hadoop and humongous data - MongoSV 2012
Big data for the rest of us
OSCON 2012 MongoDB Tutorial
Replication, Durability, and Disaster Recovery
Multi Data Center Strategies
NoSQL databases and managing big data
MongoDB, Hadoop and Humongous Data

Recently uploaded (20)

PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
PPTX
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
PDF
NewMind AI Monthly Chronicles - July 2025
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Advanced IT Governance
PDF
Sensors and Actuators in IoT Systems using pdf
PPTX
Big Data Technologies - Introduction.pptx
PDF
KodekX | Application Modernization Development
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PPTX
Cloud computing and distributed systems.
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Chapter 2 Digital Image Fundamentals.pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
NewMind AI Monthly Chronicles - July 2025
Understanding_Digital_Forensics_Presentation.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Advanced IT Governance
Sensors and Actuators in IoT Systems using pdf
Big Data Technologies - Introduction.pptx
KodekX | Application Modernization Development
Dropbox Q2 2025 Financial Results & Investor Presentation
Per capita expenditure prediction using model stacking based on satellite ima...
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Cloud computing and distributed systems.
“AI and Expert System Decision Support & Business Intelligence Systems”
Reach Out and Touch Someone: Haptics and Empathic Computing
Chapter 2 Digital Image Fundamentals.pdf
Chapter 3 Spatial Domain Image Processing.pdf

MongoDB and PHP ZendCon 2011

  • 2. My name is Steve Francia @spf13
  • 3. • 15+ years building the internet • Father, husband, skateboarder • Chief Solutions Architect @ 10gen • Author of upcoming O’Reilly publication “PHP and MongoDB”
  • 4. Introduction to MongoDB
  • 6. MongoDB Goals • OpenSource • Designed for today • Today’s hardware / environments • Today’s challenges • Easy development • Reliable • Scalable
  • 7. • Company behind MongoDB • AGPL license, own copyrights, engineering team • support, consulting, commercial license revenue • Management • Google/DoubleClick, Oracle, Apple, NetApp • Funding: Sequoia, Union Square, Flybridge • Offices in NYC, Redwood Shores & London • 60+ employees
  • 8. A bit of history
  • 12. 1979
  • 13. 1979 1982-1996
  • 14. 1979 1982-1996 1995
  • 15. Computers in 1995 •Pentium 100 mhz •10base T •16 MB ram •200 MB HD
  • 16. Cell Phones in 2011 •Dual core 1.5 Ghz •WiFi 802.11n (300+ Mbps) •1 GB ram •64GB Solid State
  • 17. How about a DB designed for today?
  • 18. It started with DoubleClick
  • 19. Signs something needed •doubleclick - 400,000 ads/second •caching is de rigueur •complex ORM frameworks •computer architecture increasing in complexity •cloud computing
  • 20. Requirements We need enough functionality to handle broad set of use cases •strong consistency / atomicity •secondary indexes •ad hoc queries
  • 21. Trim unneeded features Leave out a few things so we can scale •no choice but to leave out relational •distributed transactions are hard to scale
  • 22. Needed a scalable data model Considered.... •key/value •columnar / tabular •document oriented (JSON inspired)
  • 23. MongoDB philosphy • Keep functionality when we can (key/ value stores are great, but we need more) • Non-relational (no joins) makes scaling horizontally practical • Document data models are good • Database technology should run anywhere VMs, cloud or straight metal
  • 24. MongoDB is: Application Document Oriented { author: “steve”, High date: new Date(), text: “About MongoDB...”, Performance tags: [“tech”, “database”]} Fully Consistent Horizontally Scalable
  • 25. MongoDB •JSON Documents •Querying/Indexing/Updating similar to relational databases •Traditional Consistency •Auto-Sharding
  • 26. Under the hood •Written in C++ •Available on most platforms •Data serialized to BSON •Extensive use of memory-mapped files
  • 28. This has led some to say “ MongoDB has the best features of key/ values stores, document databases and relational databases in one. John Nunemaker
  • 30. CMS / Blog Needs: • Business needed modern data store for rapid development and scale Solution: • Use PHP & MongoDB Results: • Real time statistics • All data, images, etc stored together, easy access, easy deployment, easy high availability • No need for complex migrations • Enabled very rapid development and growth
  • 31. Photo Meta-Data Problem: • Business needed more flexibility than Oracle could deliver Solution: • Use MongoDB instead of Oracle Results: • Developed application in one sprint cycle • 500% cost reduction compared to Oracle • 900% performance improvement compared to Oracle
  • 32. Customer Analytics Problem: • Deal with massive data volume across all customer sites Solution: • Use MongoDB to replace Google Analytics / Omniture options Results: • Less than one week to build prototype and prove business case • Rapid deployment of new features
  • 33. Online Dictionary Problem: • MySQL could not scale to handle their 5B+ documents Solution: • Switched from MySQL to MongoDB Results: • Massive simplification of code base • Eliminated need for external caching system • 20x performance improvement over MySQL
  • 34. E-commerce Problem: • Multi-vertical E-commerce impossible to model (efficiently) in RDBMS Solution: • Switched from MySQL to MongoDB Results: • Massive simplification of code base • Rapidly build, halving time to market (and cost) • Eliminated need for external caching system • 50x+ improvement over MySQL
  • 35. Tons more Pretty much if you can use a RDMBS or Key/Value MongoDB is a great fit
  • 38. Relational made normalized data look like this
  • 39. Document databases make normalized data look like this
  • 40. Terminology RDBMS Mongo Table, View ➜ Collection Row ➜ JSON Document Index ➜ Index Join ➜ Embedded Document Partition ➜ Shard Partition Key ➜ Shard Key
  • 41. Documents to Objects Documents to Arrays Tables to Documents { PostObject Object( [title] => MongoDB title: ‘MongoDB’, [contributors] => Array( contributors: [ [0] => PersonObject Object( { name: ‘Eliot Horowitz’, [name] => Eliot Horowitz [email] => [email protected] email: ‘[email protected]’ }, ) { name: PersonObjectMerriman’, [1] => ‘Dwight Object( email: ‘[email protected]’ } [name] => Dwight Merriman [email] => [email protected] ], ) model: { ) relational: false, [model] => ModelObject Object( [relational] => awesome:=>true [awesome] 1 }) ) }
  • 42. Documents to Objects Documents to Arrays Tables to Documents { array( PostObject Object( title: ‘MongoDB’, "title" =>=> MongoDB [title] 'MongoDB', "contributors" =>=> Array( [contributors] array( contributors: [ array( => PersonObject Object( [0] { name: ‘Eliot Horowitz’, 'name' => 'Eliot Horowitz', [name] => Eliot Horowitz email: ‘[email protected]’ }, 'email' => '[email protected]' [email] => [email protected] ), ) { name: ‘Dwight Merriman’, array( => PersonObject Object( [1] email: ‘[email protected]’ } 'name' => 'Dwight Merriman', [name] => Dwight Merriman 'email' => '[email protected]' [email] => [email protected] ], ) ) model: { ),) relational: false, "model" =>=> ModelObject Object( [model] array( 'relational' => false, [relational] awesome: true 'awesome' => true [awesome] 1 } ) ) } )
  • 43. Documents to Objects Documents to Arrays Tables to Documents { array( PostObject Object( title: ‘MongoDB’, "title" =>=> MongoDB [title] 'MongoDB', "contributors" =>=> Array( [contributors] array( contributors: [ array( => PersonObject Object( [0] { name: ‘Eliot Horowitz’, 'name' => 'Eliot Horowitz', [name] => Eliot Horowitz email: ‘[email protected]’ }, 'email' => '[email protected]' [email] => [email protected] ), ) { name: ‘Dwight Merriman’, array( => PersonObject Object( [1] email: ‘[email protected]’ } 'name' => 'Dwight Merriman', [name] => Dwight Merriman 'email' => '[email protected]' [email] => [email protected] ], ) ) model: { ),) relational: false, "model" =>=> ModelObject Object( [model] array( 'relational' => false, [relational] awesome: true 'awesome' => true [awesome] 1 } ) ) } )
  • 45. This has led some to say “ The single best interface (API) of any php extension.   Matthew Weier O'Phinney
  • 46. PHP Driver Installing the driver $ pecl install mongo Add to php.ini extension = mongo.so
  • 47. Connecting to the DB $connection = new Mongo(); $db = $connection->selectDB('blog'); $posts = $db->post; If the DB or collection doesn’t exist, mongoDB will create it on connect.
  • 48. Documents Blog Post Document $p1 = array("author" => "roger", "date" => new MongoDate(), "text" => "about mongoDB...", "tags" => array('tech', 'databases') ); $posts->save($p1);
  • 49. Querying print_r($posts->findOne()); > db.posts.findOne() Array( [_id] => MongoId Object( > { _id : ObjectId("4c4ba5c0672c685e5e8aabf3"), [$id] => 4e9796764a18173a17000000 author : "roger", ) date : "Sat Jul 24 2010 19:47:11", [author] => roger text : "About MongoDB...", [date] => MongoDate Object( tags : [ "tech", "databases" ] } [sec] => 1318557302 [usec] => 581000 ) [text] => about mongoDB... [tags] => Array( Note: _id is unique, but can be anything [0] => tech [1] => databases you’d like ) )
  • 50. Querying print_r($posts->findOne()); > db.posts.findOne() Array( [_id] => MongoId Object( > { _id : ObjectId("4c4ba5c0672c685e5e8aabf3"), [$id] => 4e9796764a18173a17000000 author : "roger", ) date : "Sat Jul 24 2010 19:47:11", [author] => roger text : "About MongoDB...", [date] => MongoDate Object( tags : [ "tech", "databases" ] } [sec] => 1318557302 [usec] => 581000 ) [text] => about mongoDB... [tags] => Array( Note: _id is unique, but can be anything [0] => tech [1] => databases you’d like ) )
  • 51. Inserting Objects class PostObj { public $comments = array(); public function __construct($author, $title, $content) { $this->author = $author; $this->title = $title; $this->content = $content; } } $posts->insert(new PostObj("Steve", "My first blog post", "Hello, World!"));
  • 52. MongoId An autogenerated primary key $x = array("foo" => 1, "bar" => 2); $db->baz->save($x); var_dump($x['_id']); Result: object(MongoId)#4 (1) { ["$id"]=> string(24) "4e9cc76a4a1817fd21000000" }
  • 53. MongoId An autogenerated primary key object(MongoId)#4 (1) { ["$id"]=> string(24) "4e9cc76a4a1817fd21000000" } 4e9cc76a4a1817fd21000000 |------||----||--||----| ts mac pid inc
  • 54. Update Operations $set, $unset, $inc, $push, $pushAll, $pull, $pullAll, $bit $change = array('$push' => array('comments' => array( 'author' => 'Fred', 'created' => new MongoDate(), 'comment' => 'Best post ever!.' ) ) ); $posts->update(array("_id" => $id), $change);
  • 55. Nested Documents Array( { _id : ObjectId("4c4ba5c0672c685e5e8aabf3"), [_id] => MongoId Object ( [$id] => 4e9796764a18173a17000000 ) author : "roger", [author] => roger date : "Sat Apr 24 2011 19:47:11", [comments] => Array( text : "About MongoDB...", [0] => Array( [author] => Fred tags : [ "tech", "databases" ], [created] => MongoDate Object( [sec] => 1318899392 comments : [ [usec] => 176000 ) { [comment] => Dumb post. ) ) author : "Fred", [date] => MongoDate Object( date : "Sat Apr 25 2010 20:51:03 GMT-0700", [sec] => 1318557302 [usec] => 581000 ) text : "Best Post Ever!" [tags] => Array( } [0] => tech ) ] [1] => databases } ) [text] => about mongoDB...
  • 56. Nested Documents Array( { _id : ObjectId("4c4ba5c0672c685e5e8aabf3"), [_id] => MongoId Object ( [$id] => 4e9796764a18173a17000000 ) author : "roger", [author] => roger date : "Sat Apr 24 2011 19:47:11", [comments] => Array( text : "About MongoDB...", [0] => Array( [author] => Fred tags : [ "tech", "databases" ], [created] => MongoDate Object( [sec] => 1318899392 comments : [ [usec] => 176000 ) { [comment] => Dumb post. ) ) author : "Fred", [date] => MongoDate Object( date : "Sat Apr 25 2010 20:51:03 GMT-0700", [sec] => 1318557302 [usec] => 581000 ) text : "Best Post Ever!" [tags] => Array( } [0] => tech ) ] [1] => databases } ) [text] => about mongoDB...
  • 57. Querying $posts = $blog->find(array( "author" => "Roger")); $commentsByFred = $blog->find(array( "comments.author" => "Fred")); $commentsByFred = $blog->find(array( "comments.author" => new MongoRegex("/fred/i")));
  • 58. It’s all about the $ $ instead of >, <, =, etc. $gt, $gte, $lt, $lte, $eq, $neq, $exists, $set, $mod, $where, $in, $nin, $inc $push, $pull, $pop, $pushAll, $popAll $c->find(array("x" => array('$gt' => 4))); $c->find(array("x" => array(“$gt” => 4)));
  • 59. It’s all about the $ $ instead of >, <, =, etc. $gt, $gte, $lt, $lte, $eq, $neq, $exists, $set, $mod, $where, $in, $nin, $inc $push, $pull, $pop, $pushAll, $popAll $c->find(array("x" => array('$gt' => 4))); $c->find(array("x" => array(“$gt” => 4)));
  • 60. Adjust the behavior in php.ini or using ini_set() php.ini --------------- mongo.cmd = ":" $c->find(array("x" => array(':gt' => 4))); or ini_set("mongo.cmd", "."); $c->find(array("x" => array('.gt' => 4)));
  • 61. Indexing including secondary and compound indexes $people->ensureIndex(array("age" => 1)); $people->ensureIndex(array( "name" => -1, "ts" => -1, "comments.author" => 1 ));
  • 62. More Indexing // Index nested documents $posts->ensureIndex( array("comments.author" => 1) ) $posts->find( array("comments.author" => "Fred") ) // Index on tags (multi-key index) $posts->ensureIndex( array("tags" => 1 ) ) $posts->find( array("tags" => "tech") ) // geospatial index $posts->ensureIndex( array("author.location" => "2d") ) $posts->find( array("author.location" => array( '$near' => array(22,42)));
  • 63. Cursors $cursor = $c->find(array("foo" => "bar")) foreach ($cursor as $id => $value) { echo "$id: "; var_dump( $value ); } $a = iterator_to_array($cursor);
  • 64. Paging $page_num = 3; $results_per_page = 10; $cursor = $results->find() ->sort(array("ts" => -1)) ->skip($page_num * $results_per_page) ->limit($results_per_page);
  • 65. Rich Documents { _id : ObjectId("4c4ba5c0672c685e5e8aabf3"), line_items : [ { sku: ‘tt-123’, name: ‘Coltrane: Impressions’ }, { sku: ‘tt-457’, name: ‘Davis: Kind of Blue’ } ], address : { name: ‘Banker’, street: ‘111 Main’, zip: 10010 }, payment: { cc: 4567, exp: Date(2011, 7, 7) }, subtotal: 2355 }
  • 68. Storing Big Files >16mb stored in 16mb chunks
  • 69. Storing Big Files Works with replicated and sharded systems
  • 70. A better network FS • GridFS files are seamlessly sharded & replicated. • No OS constraints... • No file size limits • No naming constraints • No folder limits • Standard across different OSs • MongoDB automatically generate the MD5 hash of the file
  • 71. Storing Files $grid = $db->getGridFS(); // The file's location in the File System $path = "/tmp/"; $filename = "movie.mp4"; // Note metadata field & filename field $storedfile = $grid->storeFile($path . $filename, array("metadata" => array("filename" => $filename), "filename" => $filename)); // Return newly stored file's Document ID echo $storedfile;
  • 72. Storing Data $grid = $db->getGridFS(); $filename = "zelda.jpg"; $storedfile = $grid->storeBytes("√ø√ò√ø√⠀ ^@^PJFIF^@^A^A^A,^G^E^E^G,...", array("metadata" => array("filename" => $filename), "filename" => $filename));
  • 73. Streaming Data $gridFS = $db->getGridFS(); // Find image to stream $image = $gridFS->findOne("zelda.jpg"); // Stream image to browser header('Content-type: image/jpeg'); echo $image->getBytes();
  • 74. PHP Libraries for MongoDB
  • 75. Libraries & Frameworks • Doctrine MongoDB ODM • Zend Framework • Active Mongo • Lithium • Mongo Queue • Symfony2 • Morph • Fuel • Mandango • Fat Free Framework
  • 76. Doctrine MongoDB ODM • Provides full validation • Seamless integration with Doctrine ORM • Useful for hybrid solutions • Follows same persistence model as Doctrine • Uses a Document Manager & annotations • Supports embedded and referenced objects • Can use mongo’s query interface • Supports in place updates https://github.com/doctrine/mongodb-odm
  • 77. Mandango •Very light and fast •Event support •Supports embedded and referenced objects •uses the mongo query syntax •Lacking validation, but events can be utilized to validate https://github.com/mandango/mandango
  • 78. Active Mongo •Uses ActiveRecord (active document) interface •Supports full validation •Supports in place updating •Uses native query interface •Supports referenced documents https://github.com/crodas/ActiveMongo
  • 79. Morph •Follows the Active Record model •Has own query object (Morph_Query) •Doesn’t provide validation •Doesn’t support embedded or referenced objects. https://github.com/a-musing-moose/morph
  • 80. Mongo Queue An extensible job/message queueing system that uses mongodb as the persistent storage engine. • Fully Configurable • Distributed • Atomic Locking • Priority Support • Worker Timeout Support • Stable https://github.com/skiz/mongo_queue
  • 81. http://spf13.com http://github.com/spf13 @spf13 Questions? download at mongodb.org PS: We’re hiring!! Contact us at [email protected]

Editor's Notes

  • #2: \n
  • #3: \n
  • #4: \n
  • #5: \n
  • #6: \n
  • #7: \n
  • #8: \n
  • #9: \n
  • #10: \n
  • #11: \n
  • #12: Remember in 1995 there were around 10,000 websites. Mosiac, Lynx, Mozilla (pre netscape) and IE 2.0 were the only web browsers. \nApache (Dec &amp;#x2019;95), Java (&amp;#x2019;96), PHP (June &amp;#x2019;95), and .net didn&amp;#x2019;t exist yet. Linux just barely (1.0 in &amp;#x2019;94)\n
  • #13: Remember in 1995 there were around 10,000 websites. Mosiac, Lynx, Mozilla (pre netscape) and IE 2.0 were the only web browsers. \nApache (Dec &amp;#x2019;95), Java (&amp;#x2019;96), PHP (June &amp;#x2019;95), and .net didn&amp;#x2019;t exist yet. Linux just barely (1.0 in &amp;#x2019;94)\n
  • #14: Remember in 1995 there were around 10,000 websites. Mosiac, Lynx, Mozilla (pre netscape) and IE 2.0 were the only web browsers. \nApache (Dec &amp;#x2019;95), Java (&amp;#x2019;96), PHP (June &amp;#x2019;95), and .net didn&amp;#x2019;t exist yet. Linux just barely (1.0 in &amp;#x2019;94)\n
  • #15: \n
  • #16: \n
  • #17: \n
  • #18: \n
  • #19: \n
  • #20: \n
  • #21: \n
  • #22: \n
  • #23: By reducing transactional semantics the db provides, one can still solve an interesting set of problems where performance is very important, and horizontal scaling then becomes easier.\n\n
  • #24: \n
  • #25: \n
  • #26: \n
  • #27: \n
  • #28: \n
  • #29: \n
  • #30: \n
  • #31: \n
  • #32: \n
  • #33: \n
  • #34: \n
  • #35: \n
  • #36: \n
  • #37: \n
  • #38: \n
  • #39: \n
  • #40: \n
  • #41: \n
  • #42: \n
  • #43: \n
  • #44: \n
  • #45: \n
  • #46: \n
  • #47: \n
  • #48: \n
  • #49: \n
  • #50: \n
  • #51: \n
  • #52: \n
  • #53: \n
  • #54: \n
  • #55: \n
  • #56: \n
  • #57: \n
  • #58: \n
  • #59: \n
  • #60: \n
  • #61: \n
  • #62: \n
  • #63: \n
  • #64: \n
  • #65: \n
  • #66: \n
  • #67: \n
  • #68: \n
  • #69: \n
  • #70: \n
  • #71: \n
  • #72: \n
  • #73: \n
  • #74: \n
  • #75: \n
  • #76: \n
  • #77: \n
  • #78: \n
  • #79: \n
  • #80: \n
  • #81: \n
  • #82: \n
  • #83: \n
  • #84: \n