KEMBAR78
Getting started with MongoDB and PHP | ODP
MongoDB & PHP - Welcome What we'll cover: MongoDB quick overview
Setting up MongoDB + PHP
Actual PHP code! (https://github.com/gatesvp/php_get_started) © Copyright 2011 10gen Inc.
MongoDB & PHP – Who Am I? { name: 'Gaëtan (Gates) Voyer-Perrault', job_title: 'Customer Success Engineer', email: 'gates@10gen.com', twitter: '@gatesvp', specialties: [ 'php', 'content monetization',  'mongodb', 'powershell', ':)' ] } © Copyright 2011 10gen Inc.
What is MongoDB? From the website:  “Scalable, high-performance, document-oriented database” : So it's a database, with specific features: Data is stored in BSON ( think JSON )
Native arrays, nested documents
Indexing for faster queries
Map / Reduce for aggregation © Copyright 2011 10gen Inc.
What is MongoDB?   Document-oriented Databases contains Collections Collections contain Documents © Copyright 2011 10gen Inc.
What is MongoDB?   Document-oriented Collections are basically “bags of documents”. In our case, bags of JSON objects. Different Fields
Different Sizes
Indexable © Copyright 2011 10gen Inc.
What is MongoDB?   Scalable Read scaling and HA  via  Replication © Copyright 2011 10gen Inc.
What is MongoDB?   Scalable Write scaling via  Sharding © Copyright 2011 10gen Inc.
Installing MongoDB & PHP Installing MongoDB: Download your version http://www.mongodb.org/downloads On Linux: $ curl http://downloads.mongodb.org/linux/mongodb-linux-x86_64-1.8.1.tgz > mongo.tgz $ tar xzf mongo.tgz $ sudo mkdir -p /data/db/ $ sudo chown `id -u` /data/db $ ./mongodb-xxxxxxx/bin/mongod © Copyright 2011 10gen Inc.
Installing MongoDB & PHP Installing PHP Driver: $ sudo apt-get install php5-dev php5-cli php-pear $ sudo pecl install mongo Open  php.ini  file and add: extension=mongo.so © Copyright 2011 10gen Inc.
Let's start saving documents Basic Connection: <?php try { $mongo = new Mongo('localhost:27017');  // default $db = $mongo->example; $collection = $db->test; $document = array('x' => 1); $collection->insert($document); print_r($document); } catch(Exception $e) { print($e->getMessage()); } ?> © Copyright 2011 10gen Inc.
Saving – Some notes When we insert the document, a couple of “magic” things happen: The  example  DB is created
The  test  collection is created
An index is created the  _id  field
An  _id  is created for the document
The  _id  is added to the document © Copyright 2011 10gen Inc.
A more complex document JSON representation Notice the friends array, contact sub-document. { _id : 'gates', name : 'Gaëtan Voyer-Perrault', friends : ['bernie', 'alvin'], followers : 18, contact : { twitter : '@gatesvp', email : 'gates@10gen.com' } } © Copyright 2011 10gen Inc.
A more complex document PHP representation Nested hashtables $doc = array( '_id' => 'gates', 'name' => 'Gaëtan Voyer-Perrault', 'friends' => array('bernie', 'alvin'), 'followers' => 18, 'contact' => array( 'twitter' =>  '@gatesvp ', 'email' =>  'gates@10gen.com ') ) ) © Copyright 2011 10gen Inc.
Some Basic Queries Queries accept a document / hashtable: // Basic query $query = array( '_id' => 'gates'); $result = $collection->findOne($query); // Query on array $query = array( 'friends' => 'alvin'); $result = $collection->findOne($query); // Query on sub-document $query = array( 'contact.twitter' => '@gatesvp'); $result = $collection->findOne($query); © Copyright 2011 10gen Inc.
Some Basic Queries – less fields Queries can specify only certain fields // Filter fields $query = array( '_id' => 'gates'); $fields = array( '_id' => 0, 'name' => 1, 'friends' => 1); $result = $collection->findOne($query, $fields); © Copyright 2011 10gen Inc.
Some Advanced Queries Mongo has several $operators: // Greater than ($gt) $query = array( 'followers' => array( '$gt' => 10 ) ); $results = $collection->find($query); // IN ($in) $query = array( '_id' =>  array( '$in' => array('gates','jim') ) ); $results = $collection->find($query); // also support for $or, $exists, $mod, $type, $size // regexes and negated versions of these. © Copyright 2011 10gen Inc.
Cursoring through results Result of a find() is cursor. Cursor works with foreach. $collection->insert(array('x' => 1)); $collection->insert(array('x' => 2)); $collection->insert(array('x' => 3)); $results = $collection->find(); foreach($results as $r) {  print_r($r); } © Copyright 2011 10gen Inc.
Cursoring through results Alternately works with while loop: $collection->insert(array('x' => 1)); $collection->insert(array('x' => 2)); $collection->insert(array('x' => 3)); $results = $collection->find(); while($results->getNext()){ $r = $results->hasNext(); print_r($r); } © Copyright 2011 10gen Inc.
Cursoring through results Cursor also does counting, skipping, limiting: // Greater than ($gt) $collection->insert(array('x' => 1)); $collection->insert(array('x' => 2)); $collection->insert(array('x' => 3)); print($collection->find()->count());  // 3 $res = $collection->find()->limit(1);  // x=>1 $res2 = $collection->find()->skip(1)->limit(1);  // x=>2 © Copyright 2011 10gen Inc.
Updating Documents Query + Update command // Does not behave as you would expect $query = array( '_id' => 'gates' ); $update = array( 'followers' => 19 ); $collection->update($query, $update); // Instead $query = array( '_id' => 'gates' ); $update = array( ' $set ' => array('followers' => 19) ); $collection->update($query, $update); © Copyright 2011 10gen Inc.
Updating Documents Other operators // Instead $query = array( '_id' => 'gates' ); $update = array( ' $set ' => array('name' => 'GVP',  'contact.website' => ' http://10gen.com/ '), ' $inc ' => array('followers' => 1), ' $push ' => array('friends' => 'antoine'), ' $unset ' => array('contact.twitter' => 1) ); $collection->update($query, $update); © Copyright 2011 10gen Inc.
More on updating There are several more operators $push, $pop, $pull, $addToSet $rename
Operators are atomic within a document.
Only one operation per field. You cannot  $pop  &  $pull  an array in one command. © Copyright 2011 10gen Inc.

Getting started with MongoDB and PHP

  • 1.
    MongoDB & PHP- Welcome What we'll cover: MongoDB quick overview
  • 2.
  • 3.
    Actual PHP code!(https://github.com/gatesvp/php_get_started) © Copyright 2011 10gen Inc.
  • 4.
    MongoDB & PHP– Who Am I? { name: 'Gaëtan (Gates) Voyer-Perrault', job_title: 'Customer Success Engineer', email: 'gates@10gen.com', twitter: '@gatesvp', specialties: [ 'php', 'content monetization', 'mongodb', 'powershell', ':)' ] } © Copyright 2011 10gen Inc.
  • 5.
    What is MongoDB?From the website: “Scalable, high-performance, document-oriented database” : So it's a database, with specific features: Data is stored in BSON ( think JSON )
  • 6.
  • 7.
  • 8.
    Map / Reducefor aggregation © Copyright 2011 10gen Inc.
  • 9.
    What is MongoDB? Document-oriented Databases contains Collections Collections contain Documents © Copyright 2011 10gen Inc.
  • 10.
    What is MongoDB? Document-oriented Collections are basically “bags of documents”. In our case, bags of JSON objects. Different Fields
  • 11.
  • 12.
    Indexable © Copyright2011 10gen Inc.
  • 13.
    What is MongoDB? Scalable Read scaling and HA via Replication © Copyright 2011 10gen Inc.
  • 14.
    What is MongoDB? Scalable Write scaling via Sharding © Copyright 2011 10gen Inc.
  • 15.
    Installing MongoDB &PHP Installing MongoDB: Download your version http://www.mongodb.org/downloads On Linux: $ curl http://downloads.mongodb.org/linux/mongodb-linux-x86_64-1.8.1.tgz > mongo.tgz $ tar xzf mongo.tgz $ sudo mkdir -p /data/db/ $ sudo chown `id -u` /data/db $ ./mongodb-xxxxxxx/bin/mongod © Copyright 2011 10gen Inc.
  • 16.
    Installing MongoDB &PHP Installing PHP Driver: $ sudo apt-get install php5-dev php5-cli php-pear $ sudo pecl install mongo Open php.ini file and add: extension=mongo.so © Copyright 2011 10gen Inc.
  • 17.
    Let's start savingdocuments Basic Connection: <?php try { $mongo = new Mongo('localhost:27017'); // default $db = $mongo->example; $collection = $db->test; $document = array('x' => 1); $collection->insert($document); print_r($document); } catch(Exception $e) { print($e->getMessage()); } ?> © Copyright 2011 10gen Inc.
  • 18.
    Saving – Somenotes When we insert the document, a couple of “magic” things happen: The example DB is created
  • 19.
    The test collection is created
  • 20.
    An index iscreated the _id field
  • 21.
    An _id is created for the document
  • 22.
    The _id is added to the document © Copyright 2011 10gen Inc.
  • 23.
    A more complexdocument JSON representation Notice the friends array, contact sub-document. { _id : 'gates', name : 'Gaëtan Voyer-Perrault', friends : ['bernie', 'alvin'], followers : 18, contact : { twitter : '@gatesvp', email : 'gates@10gen.com' } } © Copyright 2011 10gen Inc.
  • 24.
    A more complexdocument PHP representation Nested hashtables $doc = array( '_id' => 'gates', 'name' => 'Gaëtan Voyer-Perrault', 'friends' => array('bernie', 'alvin'), 'followers' => 18, 'contact' => array( 'twitter' => '@gatesvp ', 'email' => 'gates@10gen.com ') ) ) © Copyright 2011 10gen Inc.
  • 25.
    Some Basic QueriesQueries accept a document / hashtable: // Basic query $query = array( '_id' => 'gates'); $result = $collection->findOne($query); // Query on array $query = array( 'friends' => 'alvin'); $result = $collection->findOne($query); // Query on sub-document $query = array( 'contact.twitter' => '@gatesvp'); $result = $collection->findOne($query); © Copyright 2011 10gen Inc.
  • 26.
    Some Basic Queries– less fields Queries can specify only certain fields // Filter fields $query = array( '_id' => 'gates'); $fields = array( '_id' => 0, 'name' => 1, 'friends' => 1); $result = $collection->findOne($query, $fields); © Copyright 2011 10gen Inc.
  • 27.
    Some Advanced QueriesMongo has several $operators: // Greater than ($gt) $query = array( 'followers' => array( '$gt' => 10 ) ); $results = $collection->find($query); // IN ($in) $query = array( '_id' => array( '$in' => array('gates','jim') ) ); $results = $collection->find($query); // also support for $or, $exists, $mod, $type, $size // regexes and negated versions of these. © Copyright 2011 10gen Inc.
  • 28.
    Cursoring through resultsResult of a find() is cursor. Cursor works with foreach. $collection->insert(array('x' => 1)); $collection->insert(array('x' => 2)); $collection->insert(array('x' => 3)); $results = $collection->find(); foreach($results as $r) { print_r($r); } © Copyright 2011 10gen Inc.
  • 29.
    Cursoring through resultsAlternately works with while loop: $collection->insert(array('x' => 1)); $collection->insert(array('x' => 2)); $collection->insert(array('x' => 3)); $results = $collection->find(); while($results->getNext()){ $r = $results->hasNext(); print_r($r); } © Copyright 2011 10gen Inc.
  • 30.
    Cursoring through resultsCursor also does counting, skipping, limiting: // Greater than ($gt) $collection->insert(array('x' => 1)); $collection->insert(array('x' => 2)); $collection->insert(array('x' => 3)); print($collection->find()->count()); // 3 $res = $collection->find()->limit(1); // x=>1 $res2 = $collection->find()->skip(1)->limit(1); // x=>2 © Copyright 2011 10gen Inc.
  • 31.
    Updating Documents Query+ Update command // Does not behave as you would expect $query = array( '_id' => 'gates' ); $update = array( 'followers' => 19 ); $collection->update($query, $update); // Instead $query = array( '_id' => 'gates' ); $update = array( ' $set ' => array('followers' => 19) ); $collection->update($query, $update); © Copyright 2011 10gen Inc.
  • 32.
    Updating Documents Otheroperators // Instead $query = array( '_id' => 'gates' ); $update = array( ' $set ' => array('name' => 'GVP', 'contact.website' => ' http://10gen.com/ '), ' $inc ' => array('followers' => 1), ' $push ' => array('friends' => 'antoine'), ' $unset ' => array('contact.twitter' => 1) ); $collection->update($query, $update); © Copyright 2011 10gen Inc.
  • 33.
    More on updatingThere are several more operators $push, $pop, $pull, $addToSet $rename
  • 34.
    Operators are atomicwithin a document.
  • 35.
    Only one operationper field. You cannot $pop & $pull an array in one command. © Copyright 2011 10gen Inc.
  • 36.
    Updating multiples Bedefault, only first doc is updated. We can change this. $collection->insert(array('x'=>1)); $collection->insert(array('x'=>1)); $collection->insert(array('x'=>3)); $query = array('x' => 1); $update = array(' $inc ' => array('x' => 1))); $options = array(' multiple ' => true); $collection->update($query, $update, $options ); © Copyright 2011 10gen Inc.
  • 37.
    Deleting Very similarto updating. $collection->remove(); // deletes everything! $query = array('x' => 1); $collection->remove($query); // deletes where x=>1 Beware empty query! © Copyright 2011 10gen Inc.
  • 38.
    Update if notexist We call this the ' upsert ' // Upsert $query = array('_id' => 'gates'); $update = array('$inc' => array('followers' => 1)); $options = array(' upsert ' => true); $collection->update($query, $update, $options ); © Copyright 2011 10gen Inc.
  • 39.
    A word abouttransactions MongoDB does not have joins. Likewise: … no transactions across documents
  • 40.
    … notransactions across collections If you need these take a look at findAndModify + two-phase commit © Copyright 2011 10gen Inc.
  • 41.
    A word aboutexceptions Catch them. Especially when using Replica Sets. Failover is not instant. © Copyright 2011 10gen Inc.
  • 42.
    More words aboutexceptions Timeouts you'll want to check or set. Connection timeouts: try{ $connString = 'server1:27017'; $connOptions = array('timeout' => 3000); // 3 seconds $mongo = new Mongo($connString, $connOptions); } catch(MongoConnectionException $ex){ // log } © Copyright 2011 10gen Inc.
  • 43.
    More words aboutexceptions Timeouts you'll want to check or set. Cursor timeouts: try{ ... $res = $coll->find($query)->timeout(1000) // 1 second while($res->hasNext()){ $data = $res->getNext(); } } catch(MongoCursorException $ex){ // log } catch(MongoCursorTimeoutException $ex){ // log } © Copyright 2011 10gen Inc.
  • 44.
    A word aboutarrays PHP arrays are a funny beast. Take the following doc $document = array( 'normal' => array('first','second'), 'crazy' => array(&quot;0&quot; => 'first', '1' => 'second'), 'arrayObj' => new ArrayObject(array('first', 'second')), 'object' => array('1' => 'first', '2' => 'second') ); $collection->insert($document); © Copyright 2011 10gen Inc.
  • 45.
    A word aboutarrays $push only works on arrays as stored in the DB. $collection->update(array(), // works array('$push' => array('normal' => 'third')), array('$push' => array('crazy' => 'third')), // fails array('$push' => array('object' => 'third')), array('$push' => array('arrayObj' => 'third')) ); © Copyright 2011 10gen Inc.
  • 46.
    Other features MongoDB has lots of other features. DB commands : accessible from PHP
  • 47.
    GridFS : storelarge files
  • 48.
  • 49.
    Geo-spatial queries© Copyright 2011 10gen Inc.
  • 50.
    © Copyright 201010gen Inc. try at try.mongodb.org
  • 51.
    © Copyright 201010gen Inc. drivers at mongodb.org REST Clojure ColdFusion Delphi Erlang F# Go: gomongo Groovy Haskell Javascript Lua C C++ C# Java Javascript Perl PHP Python Ruby node.js Objective C PHP PowerShell Blog post Python Ruby Scala Scheme (PLT) Smalltalk: Dolphin Smalltalk Community Supported mongodb.org Supported
  • 52.
    © Copyright 201010gen Inc. @mongodb conferences, appearances, and meetups http://www.10gen.com/events http://bit.ly/mongofb Facebook | Twitter | LinkedIn http://linkd.in/joinmongo download at mongodb.org support, training, and this talk brought to you by