SlideShare uma empresa Scribd logo
MongoDB & PHP - Welcome What we'll cover: ,[object Object]
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: ,[object Object]
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. ,[object Object]
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: ,[object Object],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: ,[object Object]
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 ,[object Object],{ _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 ,[object Object],$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 ,[object Object]
Operators are atomic within a document.
Only one operation per field. You cannot  $pop  &  $pull  an array in one command. © Copyright 2011 10gen Inc.

Mais conteúdo relacionado

Mais procurados

Introduction to Modern Perl
Introduction to Modern PerlIntroduction to Modern Perl
Introduction to Modern PerlDave Cross
 
Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)
Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)
Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)Michael Wales
 
The Joy of Smartmatch
The Joy of SmartmatchThe Joy of Smartmatch
The Joy of SmartmatchAndrew Shitov
 
Into to DBI with DBD::Oracle
Into to DBI with DBD::OracleInto to DBI with DBD::Oracle
Into to DBI with DBD::Oraclebyterock
 
Ods Markup And Tagsets: A Tutorial
Ods Markup And Tagsets: A TutorialOds Markup And Tagsets: A Tutorial
Ods Markup And Tagsets: A Tutorialsimienc
 
Nine Ways to Use Network-Side Scripting
Nine Ways to Use Network-Side ScriptingNine Ways to Use Network-Side Scripting
Nine Ways to Use Network-Side ScriptingLori MacVittie
 
PHP and MySQL with snapshots
 PHP and MySQL with snapshots PHP and MySQL with snapshots
PHP and MySQL with snapshotsrichambra
 
Addmi 10.5-basic query-language
Addmi 10.5-basic query-languageAddmi 10.5-basic query-language
Addmi 10.5-basic query-languageodanyboy
 
Full-Text Search Explained - Philipp Krenn - Codemotion Rome 2017
Full-Text Search Explained - Philipp Krenn - Codemotion Rome 2017Full-Text Search Explained - Philipp Krenn - Codemotion Rome 2017
Full-Text Search Explained - Philipp Krenn - Codemotion Rome 2017Codemotion
 
Open Source Package PHP & MySQL
Open Source Package PHP & MySQLOpen Source Package PHP & MySQL
Open Source Package PHP & MySQLkalaisai
 

Mais procurados (20)

Introduction to Modern Perl
Introduction to Modern PerlIntroduction to Modern Perl
Introduction to Modern Perl
 
Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)
Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)
Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)
 
Ant
Ant Ant
Ant
 
RESTFul IDEAS
RESTFul IDEASRESTFul IDEAS
RESTFul IDEAS
 
Os Nixon
Os NixonOs Nixon
Os Nixon
 
The Joy of Smartmatch
The Joy of SmartmatchThe Joy of Smartmatch
The Joy of Smartmatch
 
Perl6 in-production
Perl6 in-productionPerl6 in-production
Perl6 in-production
 
Perl6 grammars
Perl6 grammarsPerl6 grammars
Perl6 grammars
 
Into to DBI with DBD::Oracle
Into to DBI with DBD::OracleInto to DBI with DBD::Oracle
Into to DBI with DBD::Oracle
 
Php
PhpPhp
Php
 
Php Basic
Php BasicPhp Basic
Php Basic
 
Ods Markup And Tagsets: A Tutorial
Ods Markup And Tagsets: A TutorialOds Markup And Tagsets: A Tutorial
Ods Markup And Tagsets: A Tutorial
 
PHP code examples
PHP code examplesPHP code examples
PHP code examples
 
Nine Ways to Use Network-Side Scripting
Nine Ways to Use Network-Side ScriptingNine Ways to Use Network-Side Scripting
Nine Ways to Use Network-Side Scripting
 
PHP and MySQL with snapshots
 PHP and MySQL with snapshots PHP and MySQL with snapshots
PHP and MySQL with snapshots
 
Crafting [Better] API Clients
Crafting [Better] API ClientsCrafting [Better] API Clients
Crafting [Better] API Clients
 
Test::Base
Test::BaseTest::Base
Test::Base
 
Addmi 10.5-basic query-language
Addmi 10.5-basic query-languageAddmi 10.5-basic query-language
Addmi 10.5-basic query-language
 
Full-Text Search Explained - Philipp Krenn - Codemotion Rome 2017
Full-Text Search Explained - Philipp Krenn - Codemotion Rome 2017Full-Text Search Explained - Philipp Krenn - Codemotion Rome 2017
Full-Text Search Explained - Philipp Krenn - Codemotion Rome 2017
 
Open Source Package PHP & MySQL
Open Source Package PHP & MySQLOpen Source Package PHP & MySQL
Open Source Package PHP & MySQL
 

Semelhante a Getting started with MongoDB and PHP

SugarCon 2010 - Best Practices for Creating Custom Apps in Sugar
SugarCon 2010 - Best Practices for Creating Custom Apps in SugarSugarCon 2010 - Best Practices for Creating Custom Apps in Sugar
SugarCon 2010 - Best Practices for Creating Custom Apps in SugarJohn Mertic
 
Modern Web Development with Perl
Modern Web Development with PerlModern Web Development with Perl
Modern Web Development with PerlDave Cross
 
PhpstudyTokyo MongoDB PHP CakePHP
PhpstudyTokyo MongoDB PHP CakePHPPhpstudyTokyo MongoDB PHP CakePHP
PhpstudyTokyo MongoDB PHP CakePHPichikaway
 
Introduction To Moco
Introduction To MocoIntroduction To Moco
Introduction To MocoNaoya Ito
 
jQuery - Doing it right
jQuery - Doing it rightjQuery - Doing it right
jQuery - Doing it rightgirish82
 
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
Rapid and Scalable Development with MongoDB, PyMongo, and MingRapid and Scalable Development with MongoDB, PyMongo, and Ming
Rapid and Scalable Development with MongoDB, PyMongo, and MingRick Copeland
 
P H P Part I I, By Kian
P H P  Part  I I,  By  KianP H P  Part  I I,  By  Kian
P H P Part I I, By Kianphelios
 
Introduction To Lamp
Introduction To LampIntroduction To Lamp
Introduction To LampAmzad Hossain
 
Graph Databases
Graph DatabasesGraph Databases
Graph DatabasesJosh Adell
 
Dealing with Legacy Perl Code - Peter Scott
Dealing with Legacy Perl Code - Peter ScottDealing with Legacy Perl Code - Peter Scott
Dealing with Legacy Perl Code - Peter ScottO'Reilly Media
 
Going crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHPGoing crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHPMariano Iglesias
 
Think Generic - Add API's To Your Custom Modules
Think Generic - Add API's To Your Custom ModulesThink Generic - Add API's To Your Custom Modules
Think Generic - Add API's To Your Custom ModulesJens Sørensen
 
Render API - Pavel Makhrinsky
Render API - Pavel MakhrinskyRender API - Pavel Makhrinsky
Render API - Pavel MakhrinskyDrupalCampDN
 
PHP Presentation
PHP PresentationPHP Presentation
PHP PresentationAnkush Jain
 
Key Value Storage Systems ... and Beyond ... with Python
Key Value Storage Systems ... and Beyond ... with PythonKey Value Storage Systems ... and Beyond ... with Python
Key Value Storage Systems ... and Beyond ... with PythonIan Lewis
 
HTML::FormHandler
HTML::FormHandlerHTML::FormHandler
HTML::FormHandlerbbeeley
 

Semelhante a Getting started with MongoDB and PHP (20)

SugarCon 2010 - Best Practices for Creating Custom Apps in Sugar
SugarCon 2010 - Best Practices for Creating Custom Apps in SugarSugarCon 2010 - Best Practices for Creating Custom Apps in Sugar
SugarCon 2010 - Best Practices for Creating Custom Apps in Sugar
 
Modern Web Development with Perl
Modern Web Development with PerlModern Web Development with Perl
Modern Web Development with Perl
 
PhpstudyTokyo MongoDB PHP CakePHP
PhpstudyTokyo MongoDB PHP CakePHPPhpstudyTokyo MongoDB PHP CakePHP
PhpstudyTokyo MongoDB PHP CakePHP
 
Web Scraping with PHP
Web Scraping with PHPWeb Scraping with PHP
Web Scraping with PHP
 
Introduction To Moco
Introduction To MocoIntroduction To Moco
Introduction To Moco
 
jQuery - Doing it right
jQuery - Doing it rightjQuery - Doing it right
jQuery - Doing it right
 
Mojolicious on Steroids
Mojolicious on SteroidsMojolicious on Steroids
Mojolicious on Steroids
 
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
Rapid and Scalable Development with MongoDB, PyMongo, and MingRapid and Scalable Development with MongoDB, PyMongo, and Ming
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
 
P H P Part I I, By Kian
P H P  Part  I I,  By  KianP H P  Part  I I,  By  Kian
P H P Part I I, By Kian
 
Introduction To Lamp
Introduction To LampIntroduction To Lamp
Introduction To Lamp
 
Graph Databases
Graph DatabasesGraph Databases
Graph Databases
 
Dealing with Legacy Perl Code - Peter Scott
Dealing with Legacy Perl Code - Peter ScottDealing with Legacy Perl Code - Peter Scott
Dealing with Legacy Perl Code - Peter Scott
 
Going crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHPGoing crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHP
 
Think Generic - Add API's To Your Custom Modules
Think Generic - Add API's To Your Custom ModulesThink Generic - Add API's To Your Custom Modules
Think Generic - Add API's To Your Custom Modules
 
Render API - Pavel Makhrinsky
Render API - Pavel MakhrinskyRender API - Pavel Makhrinsky
Render API - Pavel Makhrinsky
 
Framework
FrameworkFramework
Framework
 
PHP Presentation
PHP PresentationPHP Presentation
PHP Presentation
 
Key Value Storage Systems ... and Beyond ... with Python
Key Value Storage Systems ... and Beyond ... with PythonKey Value Storage Systems ... and Beyond ... with Python
Key Value Storage Systems ... and Beyond ... with Python
 
HTML::FormHandler
HTML::FormHandlerHTML::FormHandler
HTML::FormHandler
 
Modern Perl
Modern PerlModern Perl
Modern Perl
 

Último

Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...FIDO Alliance
 
IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIES VE
 
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka DoktorováCzechDreamin
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomCzechDreamin
 
A Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System StrategyA Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System StrategyUXDXConf
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaCzechDreamin
 
Connecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAKConnecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAKUXDXConf
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераMark Opanasiuk
 
Introduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationIntroduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationZilliz
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfFIDO Alliance
 
ECS 2024 Teams Premium - Pretty Secure
ECS 2024   Teams Premium - Pretty SecureECS 2024   Teams Premium - Pretty Secure
ECS 2024 Teams Premium - Pretty SecureFemke de Vroome
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2DianaGray10
 
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...FIDO Alliance
 
Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Patrick Viafore
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...CzechDreamin
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsStefano
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfFIDO Alliance
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekCzechDreamin
 
Agentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfAgentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfChristopherTHyatt
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?Mark Billinghurst
 

Último (20)

Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
 
IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and Planning
 
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
 
A Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System StrategyA Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System Strategy
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
Connecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAKConnecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAK
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
Introduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationIntroduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG Evaluation
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
 
ECS 2024 Teams Premium - Pretty Secure
ECS 2024   Teams Premium - Pretty SecureECS 2024   Teams Premium - Pretty Secure
ECS 2024 Teams Premium - Pretty Secure
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2
 
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
 
Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. Startups
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří Karpíšek
 
Agentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfAgentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdf
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 

Getting started with MongoDB and PHP

  • 1.
  • 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.
  • 8. Map / Reduce for aggregation © Copyright 2011 10gen Inc.
  • 9. What is MongoDB? Document-oriented Databases contains Collections Collections contain Documents © Copyright 2011 10gen Inc.
  • 10.
  • 12. Indexable © Copyright 2011 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.
  • 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 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.
  • 18.
  • 19. The test collection is created
  • 20. An index is created the _id field
  • 21. An _id is created for the document
  • 22. The _id is added to the document © Copyright 2011 10gen Inc.
  • 23.
  • 24.
  • 25. 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.
  • 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 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.
  • 28. 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.
  • 29. 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.
  • 30. 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.
  • 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 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.
  • 33.
  • 34. Operators are atomic within a document.
  • 35. Only one operation per field. You cannot $pop & $pull an array in one command. © Copyright 2011 10gen Inc.
  • 36. Updating multiples Be default, 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 similar to 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 not exist 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.
  • 40. … no transactions across collections If you need these take a look at findAndModify + two-phase commit © Copyright 2011 10gen Inc.
  • 41. A word about exceptions Catch them. Especially when using Replica Sets. Failover is not instant. © Copyright 2011 10gen Inc.
  • 42. More words about exceptions 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 about exceptions 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 about arrays 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 about arrays $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.
  • 47. GridFS : store large files
  • 49. Geo-spatial queries © Copyright 2011 10gen Inc.
  • 50. © Copyright 2010 10gen Inc. try at try.mongodb.org
  • 51. © Copyright 2010 10gen 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 2010 10gen 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