SlideShare a Scribd company logo
MongoDB Advanced Topics
          César D. Rodas
           crodas@php.net
         http://crodas.org/




     Yahoo! Open Hack Day 2010
          São Paulo, Brasil

                                 1
Who is this fellow?
         Paraguayan
         Zealot of
              • Open Source
              • PHP
              • MongoDB

         PECL Developer
         ... and few other things




@crodas - http://crodas.org/ - L EX
                               AT                           2
I'd like to thanks to...


         10gen

         Yahoo!

         My Brazilian friends




@crodas - http://crodas.org/ - L EX
                               AT                            3
Agenda
         Introduction to MongoDB
         MongoDB Queries
         Real life example:
              • Designing data model for a Wordpress.com like site
              • Optimize our data model to run in sharded environment




@crodas - http://crodas.org/ - L EX
                               AT                                       4
MongoDB
         <EN>Mongo</EN> != <PT>Mongo</PT>
         Document oriented database
         Fast, Scalable, Easy to use
         Support Indexes
              • Simple
              • Compound
              • Geo spatial

         Support sharding
         PECL client




@crodas - http://crodas.org/ - L EX
                               AT               5
Documents?



@crodas - http://crodas.org/ - L EX
                               AT                  6
It's just an Array()



@crodas - http://crodas.org/ - L EX
                               AT                7
In fact everything is an
                 Array() in MongoDB


@crodas - http://crodas.org/ - L EX
                               AT         8
http://bit.ly/mongodb-php



@crodas - http://crodas.org/ - L EX
                               AT     9
The fun part



@crodas - http://crodas.org/ - L EX
                               AT                    10
MongoDB - Operations
         Select
              • $gt, $lt, $gte, $lte, $eq, $neq: >, <, >=, <=, ==, !=
              • $in, $nin
              • $size, $exists
              • $where: Any javascript expression
              • group()
              • limit()
              • skip()

         Update
              • $set
              • $unset
              • $push
              • $pull
              • $inc


@crodas - http://crodas.org/ - L EX
                               AT                                       11
pecl install mongo



@crodas - http://crodas.org/ - L EX
                               AT              12
MongoDB - Connection


/* connects to localhost:27017 */
$connection = new Mongo();

/* connect to a remote host (default port) */
$connection = new Mongo( "example.com" );

/* connect to a remote host at a given port */
$connection = new Mongo( "example.com:65432" );

/* select some DB (and create if it doesn't exits yet) */
$db = $connection->selectDB("db name");

/* select a "table" (collection) */
$table = $db->getCollection("table");


@crodas - http://crodas.org/ - L EX
                               AT                           13
FROM SQL to MongoDB




@crodas - http://crodas.org/ - L EX
                               AT      14
MongoDB - Count

/* SELECT count(*) FROM table */
$collection->count();

/* SELECT count(*) FROM table WHERE foo = 1 */
$collection->find(array("foo" => 1))->count();




@crodas - http://crodas.org/ - L EX
                               AT                       15
MongoDB - Queries
/*
 * SELECT * FROM table WHERE field IN (5,6,7) and enable=1
 * and worth < 5
 * ORDER BY timestamp DESC
 */

$collection->ensureIndex(
   array('field'=>1, 'enable'=>1, 'worth'=>1, 'timestamp'=>-1)
);

$filter = array(
       'field' => array('$in' => array(5,6,7)),
       'enable' => 1,
       'worth' => array('$lt' => 5)
    );
$results = $collection->find($filter)->sort(array('timestamp' => -1));



@crodas - http://crodas.org/ - L EX
                               AT                                        16
MongoDB - Pagination
/*
 * SELECT * FROM table WHERE field IN (5,6,7) and enable=1
 * and worth < 5
 * ORDER BY timestamp DESC LIMIT $offset, 20
 */
$filter = array(
       'field' => array('$in' => array(5,6,7)),
       'enable' => 1,
       'worth' => array('$lt' => 5)
    );

$cursor = $collection->find($filter);
$cursor->sort(array('timestamp' => -1))->skip($offset)->limit(20);

foreach ($cursor as $result) {
   var dump($result);
}


@crodas - http://crodas.org/ - L EX
                               AT                                    17
Designing data structure
                                      Simple multi-blog system




@crodas - http://crodas.org/ - L EX
                               AT                                18
MongoDB - Collections
         Blog
         Post
         User
         Comment




@crodas - http://crodas.org/ - L EX
                               AT                         19
Blog document
$blog = array(
   "user" => <userref>,
   "title" => "Foo bar blog"
   "url" => array(
       "foobar.foobar.com",
       "anotherfoo.foobar.com",
   ),
   "permissions" => array(
       "edit" => array(<userref>, <userref>)
   );
   "post" => 1,
   ...
);




@crodas - http://crodas.org/ - L EX
                               AT                     20
Post document
$post = array(
   "blog" => <blogref>,
   "author" => <userref>,
   "uri" => "/another-post",
   "title" => "Another post",
   "excerpt" => "bla, bla, bla",
   "body" => "bar, foo bar, foo, bar",
   "tags" => array("list", "of tags"),
   "published" => true,
   "date" => <mongodate>,
);




@crodas - http://crodas.org/ - L EX
                               AT                     21
Missing docs.
$comment = array(
   "post" => <postref>,
   "name" => "foobar",
   "email" => "foo@bar.com",
   "comment" => "Hello world",
   "date" => <mongodate>,
);

$user = array(
   "user" => "crodas",
   "email" => "crodas@php.net",
   "password" => "a1bad96dc68f891ca887d50eb3fb65ec82123d05",
   "name" => "Cesar Rodas",
);




@crodas - http://crodas.org/ - L EX
                               AT                              22
About indexes

$blog col->ensureIndex(array("url" => 1));

$post col->ensureIndex(array("blog" => 1, "date" => -1));
$post col->ensureIndex(array("blog" => 1, "uri" => 1), array("unique" => 1));

$comment col->ensureIndex(array("post" => 1, "date" => -1));

$user col->ensureIndex(array("user" => 1), array("unique" => 1));
$user col->ensureIndex(array("email" => 1), array("unique" => 1));




@crodas - http://crodas.org/ - L EX
                               AT                                               23
That's it.




@crodas - http://crodas.org/ - L EX
                               AT                  24
Hum...




@crodas - http://crodas.org/ - L EX
                               AT              25
Until now, nothing new




@crodas - http://crodas.org/ - L EX
                               AT      26
Let's shard it!




@crodas - http://crodas.org/ - L EX
                               AT                       27
Strategy
         Shard Blog collection
         Shard User collection
         Other collections are isolated
              • Create namespaces for post and comments (foo.post, foo.comments)
              • Modify Blog collection, add info about "namespace" (and DB).

         MongoDB will distribute our DB and namespaces




@crodas - http://crodas.org/ - L EX
                               AT                                                  28
Configuring the sharding

/* Assuming you have already MongoDB running
 * on a sharded env., you should do this once.
 *
 * $admin is a connection to the "admin" DB.
 */
$admin->command(array(
    "shardcollection" => "blog",
    "key" => array("uri" => 1),
));

$admin->command(array(
    "shardcollection" => "user",
    "key" => array("user" => 1),
    "unique" => true,
));



@crodas - http://crodas.org/ - L EX
                               AT                        29
New blog document
$blog = array(
   "user" => <userref>,
   "title" => "Foo bar blog"
   "url" => array(
       "foobar.foobar.com",
       "anotherfoo.foobar.com",
   ),
   "permissions" => array(
       "edit" => array(<userref>, <userref>)
   );
   "post" => 1,
   "namespace" => "3h3g3k3",
   "database" => "34fs321",
);




@crodas - http://crodas.org/ - L EX
                               AT                         30
Select the DB and namespace
 to use "post" and "comments"



@crodas - http://crodas.org/ - L EX
                               AT     31
Questions?




@crodas - http://crodas.org/ - L EX
                               AT                  32
Thank you hackers!




@crodas - http://crodas.org/ - L EX
                               AT           33
MongoDB is looking from
                Brazilian help.



@crodas - http://crodas.org/ - L EX
                               AT     34
@crodas

                                      crodas.org



@crodas - http://crodas.org/ - L EX
                               AT                  35

More Related Content

What's hot

[제1회 루씬 한글분석기 기술세미나] solr로 나만의 검색엔진을 만들어보자
[제1회 루씬 한글분석기 기술세미나] solr로 나만의 검색엔진을 만들어보자[제1회 루씬 한글분석기 기술세미나] solr로 나만의 검색엔진을 만들어보자
[제1회 루씬 한글분석기 기술세미나] solr로 나만의 검색엔진을 만들어보자
Donghyeok Kang
 
Python and MongoDB
Python and MongoDBPython and MongoDB
Python and MongoDB
Christiano Anderson
 
MongoDB Europe 2016 - Advanced MongoDB Aggregation Pipelines
MongoDB Europe 2016 - Advanced MongoDB Aggregation PipelinesMongoDB Europe 2016 - Advanced MongoDB Aggregation Pipelines
MongoDB Europe 2016 - Advanced MongoDB Aggregation Pipelines
MongoDB
 
On secure application of PHP wrappers
On secure application  of PHP wrappersOn secure application  of PHP wrappers
On secure application of PHP wrappers
Positive Hack Days
 
The emerging world of mongo db csp
The emerging world of mongo db   cspThe emerging world of mongo db   csp
The emerging world of mongo db csp
Carlos Sánchez Pérez
 
MongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with MorphiaMongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with Morphia
Scott Hernandez
 
Simplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with MorphiaSimplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with Morphia
MongoDB
 
Java development with MongoDB
Java development with MongoDBJava development with MongoDB
Java development with MongoDB
James Williams
 
RESTing with the new Yandex.Disk API, Clemens Аuer
RESTing with the new Yandex.Disk API, Clemens АuerRESTing with the new Yandex.Disk API, Clemens Аuer
RESTing with the new Yandex.Disk API, Clemens Аuer
Yandex
 
MongoDB Europe 2016 - Debugging MongoDB Performance
MongoDB Europe 2016 - Debugging MongoDB PerformanceMongoDB Europe 2016 - Debugging MongoDB Performance
MongoDB Europe 2016 - Debugging MongoDB Performance
MongoDB
 
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
MongoDB
 
Back to Basics Webinar 5: Introduction to the Aggregation Framework
Back to Basics Webinar 5: Introduction to the Aggregation FrameworkBack to Basics Webinar 5: Introduction to the Aggregation Framework
Back to Basics Webinar 5: Introduction to the Aggregation Framework
MongoDB
 
Fazendo mágica com ElasticSearch
Fazendo mágica com ElasticSearchFazendo mágica com ElasticSearch
Fazendo mágica com ElasticSearch
Pedro Franceschi
 
wtf is in Java/JDK/wtf7?
wtf is in Java/JDK/wtf7?wtf is in Java/JDK/wtf7?
wtf is in Java/JDK/wtf7?
Scott Leberknight
 
"Solr Update" at code4lib '13 - Chicago
"Solr Update" at code4lib '13 - Chicago"Solr Update" at code4lib '13 - Chicago
"Solr Update" at code4lib '13 - Chicago
Erik Hatcher
 
Tthornton code4lib
Tthornton code4libTthornton code4lib
Tthornton code4lib
trevorthornton
 
Использование Elasticsearch для организации поиска по сайту
Использование Elasticsearch для организации поиска по сайтуИспользование Elasticsearch для организации поиска по сайту
Использование Elasticsearch для организации поиска по сайту
Olga Lavrentieva
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know
Norberto Leite
 
Webinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaWebinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and Morphia
MongoDB
 
OSMC 2010 | RRDCacheD - how to escape the I/O hell by Sebastian Harl
OSMC 2010 | RRDCacheD - how to escape the I/O hell by Sebastian HarlOSMC 2010 | RRDCacheD - how to escape the I/O hell by Sebastian Harl
OSMC 2010 | RRDCacheD - how to escape the I/O hell by Sebastian Harl
NETWAYS
 

What's hot (20)

[제1회 루씬 한글분석기 기술세미나] solr로 나만의 검색엔진을 만들어보자
[제1회 루씬 한글분석기 기술세미나] solr로 나만의 검색엔진을 만들어보자[제1회 루씬 한글분석기 기술세미나] solr로 나만의 검색엔진을 만들어보자
[제1회 루씬 한글분석기 기술세미나] solr로 나만의 검색엔진을 만들어보자
 
Python and MongoDB
Python and MongoDBPython and MongoDB
Python and MongoDB
 
MongoDB Europe 2016 - Advanced MongoDB Aggregation Pipelines
MongoDB Europe 2016 - Advanced MongoDB Aggregation PipelinesMongoDB Europe 2016 - Advanced MongoDB Aggregation Pipelines
MongoDB Europe 2016 - Advanced MongoDB Aggregation Pipelines
 
On secure application of PHP wrappers
On secure application  of PHP wrappersOn secure application  of PHP wrappers
On secure application of PHP wrappers
 
The emerging world of mongo db csp
The emerging world of mongo db   cspThe emerging world of mongo db   csp
The emerging world of mongo db csp
 
MongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with MorphiaMongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with Morphia
 
Simplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with MorphiaSimplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with Morphia
 
Java development with MongoDB
Java development with MongoDBJava development with MongoDB
Java development with MongoDB
 
RESTing with the new Yandex.Disk API, Clemens Аuer
RESTing with the new Yandex.Disk API, Clemens АuerRESTing with the new Yandex.Disk API, Clemens Аuer
RESTing with the new Yandex.Disk API, Clemens Аuer
 
MongoDB Europe 2016 - Debugging MongoDB Performance
MongoDB Europe 2016 - Debugging MongoDB PerformanceMongoDB Europe 2016 - Debugging MongoDB Performance
MongoDB Europe 2016 - Debugging MongoDB Performance
 
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
 
Back to Basics Webinar 5: Introduction to the Aggregation Framework
Back to Basics Webinar 5: Introduction to the Aggregation FrameworkBack to Basics Webinar 5: Introduction to the Aggregation Framework
Back to Basics Webinar 5: Introduction to the Aggregation Framework
 
Fazendo mágica com ElasticSearch
Fazendo mágica com ElasticSearchFazendo mágica com ElasticSearch
Fazendo mágica com ElasticSearch
 
wtf is in Java/JDK/wtf7?
wtf is in Java/JDK/wtf7?wtf is in Java/JDK/wtf7?
wtf is in Java/JDK/wtf7?
 
"Solr Update" at code4lib '13 - Chicago
"Solr Update" at code4lib '13 - Chicago"Solr Update" at code4lib '13 - Chicago
"Solr Update" at code4lib '13 - Chicago
 
Tthornton code4lib
Tthornton code4libTthornton code4lib
Tthornton code4lib
 
Использование Elasticsearch для организации поиска по сайту
Использование Elasticsearch для организации поиска по сайтуИспользование Elasticsearch для организации поиска по сайту
Использование Elasticsearch для организации поиска по сайту
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know
 
Webinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaWebinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and Morphia
 
OSMC 2010 | RRDCacheD - how to escape the I/O hell by Sebastian Harl
OSMC 2010 | RRDCacheD - how to escape the I/O hell by Sebastian HarlOSMC 2010 | RRDCacheD - how to escape the I/O hell by Sebastian Harl
OSMC 2010 | RRDCacheD - how to escape the I/O hell by Sebastian Harl
 

Similar to MongoDB Advanced Topics

Thinking in documents
Thinking in documentsThinking in documents
Thinking in documents
César Rodas
 
Python Web Interaction
Python Web InteractionPython Web Interaction
Python Web Interaction
Robert Sanderson
 
LibreCat::Catmandu
LibreCat::CatmanduLibreCat::Catmandu
LibreCat::Catmandu
Patrick Hochstenbach
 
Latinoware
LatinowareLatinoware
Latinoware
kchodorow
 
MongoDB a document store that won't let you down.
MongoDB a document store that won't let you down.MongoDB a document store that won't let you down.
MongoDB a document store that won't let you down.
Nurul Ferdous
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 
はじめてのMongoDB
はじめてのMongoDBはじめてのMongoDB
はじめてのMongoDB
Takahiro Inoue
 
Getting started with MongoDB and Scala - Open Source Bridge 2012
Getting started with MongoDB and Scala - Open Source Bridge 2012Getting started with MongoDB and Scala - Open Source Bridge 2012
Getting started with MongoDB and Scala - Open Source Bridge 2012
sullis
 
Ruby - Uma Introdução
Ruby - Uma IntroduçãoRuby - Uma Introdução
Ruby - Uma Introdução
Ígor Bonadio
 
DrupalCon Chicago Practical MongoDB and Drupal
DrupalCon Chicago Practical MongoDB and DrupalDrupalCon Chicago Practical MongoDB and Drupal
DrupalCon Chicago Practical MongoDB and Drupal
Doug Green
 
Introduction to Elasticsearch
Introduction to ElasticsearchIntroduction to Elasticsearch
Introduction to Elasticsearch
Sperasoft
 
9b. Document-Oriented Databases lab
9b. Document-Oriented Databases lab9b. Document-Oriented Databases lab
9b. Document-Oriented Databases lab
Fabio Fumarola
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
antoinegirbal
 
2011 Mongo FR - MongoDB introduction
2011 Mongo FR - MongoDB introduction2011 Mongo FR - MongoDB introduction
2011 Mongo FR - MongoDB introduction
antoinegirbal
 
NOSQL101, Or: How I Learned To Stop Worrying And Love The Mongo!
NOSQL101, Or: How I Learned To Stop Worrying And Love The Mongo!NOSQL101, Or: How I Learned To Stop Worrying And Love The Mongo!
NOSQL101, Or: How I Learned To Stop Worrying And Love The Mongo!
Daniel Cousineau
 
Having Fun Programming!
Having Fun Programming!Having Fun Programming!
Having Fun Programming!
Aaron Patterson
 
The Aggregation Framework
The Aggregation FrameworkThe Aggregation Framework
The Aggregation Framework
MongoDB
 
This upload requires better support for ODP format
This upload requires better support for ODP formatThis upload requires better support for ODP format
This upload requires better support for ODP format
Forest Mars
 
Webscale PostgreSQL - JSONB and Horizontal Scaling Strategies
Webscale PostgreSQL - JSONB and Horizontal Scaling StrategiesWebscale PostgreSQL - JSONB and Horizontal Scaling Strategies
Webscale PostgreSQL - JSONB and Horizontal Scaling Strategies
Jonathan Katz
 
Webinar: General Technical Overview of MongoDB for Dev Teams
Webinar: General Technical Overview of MongoDB for Dev TeamsWebinar: General Technical Overview of MongoDB for Dev Teams
Webinar: General Technical Overview of MongoDB for Dev Teams
MongoDB
 

Similar to MongoDB Advanced Topics (20)

Thinking in documents
Thinking in documentsThinking in documents
Thinking in documents
 
Python Web Interaction
Python Web InteractionPython Web Interaction
Python Web Interaction
 
LibreCat::Catmandu
LibreCat::CatmanduLibreCat::Catmandu
LibreCat::Catmandu
 
Latinoware
LatinowareLatinoware
Latinoware
 
MongoDB a document store that won't let you down.
MongoDB a document store that won't let you down.MongoDB a document store that won't let you down.
MongoDB a document store that won't let you down.
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
はじめてのMongoDB
はじめてのMongoDBはじめてのMongoDB
はじめてのMongoDB
 
Getting started with MongoDB and Scala - Open Source Bridge 2012
Getting started with MongoDB and Scala - Open Source Bridge 2012Getting started with MongoDB and Scala - Open Source Bridge 2012
Getting started with MongoDB and Scala - Open Source Bridge 2012
 
Ruby - Uma Introdução
Ruby - Uma IntroduçãoRuby - Uma Introdução
Ruby - Uma Introdução
 
DrupalCon Chicago Practical MongoDB and Drupal
DrupalCon Chicago Practical MongoDB and DrupalDrupalCon Chicago Practical MongoDB and Drupal
DrupalCon Chicago Practical MongoDB and Drupal
 
Introduction to Elasticsearch
Introduction to ElasticsearchIntroduction to Elasticsearch
Introduction to Elasticsearch
 
9b. Document-Oriented Databases lab
9b. Document-Oriented Databases lab9b. Document-Oriented Databases lab
9b. Document-Oriented Databases lab
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
2011 Mongo FR - MongoDB introduction
2011 Mongo FR - MongoDB introduction2011 Mongo FR - MongoDB introduction
2011 Mongo FR - MongoDB introduction
 
NOSQL101, Or: How I Learned To Stop Worrying And Love The Mongo!
NOSQL101, Or: How I Learned To Stop Worrying And Love The Mongo!NOSQL101, Or: How I Learned To Stop Worrying And Love The Mongo!
NOSQL101, Or: How I Learned To Stop Worrying And Love The Mongo!
 
Having Fun Programming!
Having Fun Programming!Having Fun Programming!
Having Fun Programming!
 
The Aggregation Framework
The Aggregation FrameworkThe Aggregation Framework
The Aggregation Framework
 
This upload requires better support for ODP format
This upload requires better support for ODP formatThis upload requires better support for ODP format
This upload requires better support for ODP format
 
Webscale PostgreSQL - JSONB and Horizontal Scaling Strategies
Webscale PostgreSQL - JSONB and Horizontal Scaling StrategiesWebscale PostgreSQL - JSONB and Horizontal Scaling Strategies
Webscale PostgreSQL - JSONB and Horizontal Scaling Strategies
 
Webinar: General Technical Overview of MongoDB for Dev Teams
Webinar: General Technical Overview of MongoDB for Dev TeamsWebinar: General Technical Overview of MongoDB for Dev Teams
Webinar: General Technical Overview of MongoDB for Dev Teams
 

Recently uploaded

Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 
Public CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptxPublic CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptx
marufrahmanstratejm
 
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Jeffrey Haguewood
 
Trusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process MiningTrusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process Mining
LucaBarbaro3
 
SAP S/4 HANA sourcing and procurement to Public cloud
SAP S/4 HANA sourcing and procurement to Public cloudSAP S/4 HANA sourcing and procurement to Public cloud
SAP S/4 HANA sourcing and procurement to Public cloud
maazsz111
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
Postman
 
Azure API Management to expose backend services securely
Azure API Management to expose backend services securelyAzure API Management to expose backend services securely
Azure API Management to expose backend services securely
Dinusha Kumarasiri
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Wask
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
AWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptxAWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptx
HarisZaheer8
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
Antonios Katsarakis
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
ScyllaDB
 

Recently uploaded (20)

Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 
Public CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptxPublic CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptx
 
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
 
Trusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process MiningTrusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process Mining
 
SAP S/4 HANA sourcing and procurement to Public cloud
SAP S/4 HANA sourcing and procurement to Public cloudSAP S/4 HANA sourcing and procurement to Public cloud
SAP S/4 HANA sourcing and procurement to Public cloud
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
 
Azure API Management to expose backend services securely
Azure API Management to expose backend services securelyAzure API Management to expose backend services securely
Azure API Management to expose backend services securely
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
AWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptxAWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptx
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
 

MongoDB Advanced Topics

  • 1. MongoDB Advanced Topics César D. Rodas crodas@php.net http://crodas.org/ Yahoo! Open Hack Day 2010 São Paulo, Brasil 1
  • 2. Who is this fellow? Paraguayan Zealot of • Open Source • PHP • MongoDB PECL Developer ... and few other things @crodas - http://crodas.org/ - L EX AT 2
  • 3. I'd like to thanks to... 10gen Yahoo! My Brazilian friends @crodas - http://crodas.org/ - L EX AT 3
  • 4. Agenda Introduction to MongoDB MongoDB Queries Real life example: • Designing data model for a Wordpress.com like site • Optimize our data model to run in sharded environment @crodas - http://crodas.org/ - L EX AT 4
  • 5. MongoDB <EN>Mongo</EN> != <PT>Mongo</PT> Document oriented database Fast, Scalable, Easy to use Support Indexes • Simple • Compound • Geo spatial Support sharding PECL client @crodas - http://crodas.org/ - L EX AT 5
  • 7. It's just an Array() @crodas - http://crodas.org/ - L EX AT 7
  • 8. In fact everything is an Array() in MongoDB @crodas - http://crodas.org/ - L EX AT 8
  • 10. The fun part @crodas - http://crodas.org/ - L EX AT 10
  • 11. MongoDB - Operations Select • $gt, $lt, $gte, $lte, $eq, $neq: >, <, >=, <=, ==, != • $in, $nin • $size, $exists • $where: Any javascript expression • group() • limit() • skip() Update • $set • $unset • $push • $pull • $inc @crodas - http://crodas.org/ - L EX AT 11
  • 12. pecl install mongo @crodas - http://crodas.org/ - L EX AT 12
  • 13. MongoDB - Connection /* connects to localhost:27017 */ $connection = new Mongo(); /* connect to a remote host (default port) */ $connection = new Mongo( "example.com" ); /* connect to a remote host at a given port */ $connection = new Mongo( "example.com:65432" ); /* select some DB (and create if it doesn't exits yet) */ $db = $connection->selectDB("db name"); /* select a "table" (collection) */ $table = $db->getCollection("table"); @crodas - http://crodas.org/ - L EX AT 13
  • 14. FROM SQL to MongoDB @crodas - http://crodas.org/ - L EX AT 14
  • 15. MongoDB - Count /* SELECT count(*) FROM table */ $collection->count(); /* SELECT count(*) FROM table WHERE foo = 1 */ $collection->find(array("foo" => 1))->count(); @crodas - http://crodas.org/ - L EX AT 15
  • 16. MongoDB - Queries /* * SELECT * FROM table WHERE field IN (5,6,7) and enable=1 * and worth < 5 * ORDER BY timestamp DESC */ $collection->ensureIndex( array('field'=>1, 'enable'=>1, 'worth'=>1, 'timestamp'=>-1) ); $filter = array( 'field' => array('$in' => array(5,6,7)), 'enable' => 1, 'worth' => array('$lt' => 5) ); $results = $collection->find($filter)->sort(array('timestamp' => -1)); @crodas - http://crodas.org/ - L EX AT 16
  • 17. MongoDB - Pagination /* * SELECT * FROM table WHERE field IN (5,6,7) and enable=1 * and worth < 5 * ORDER BY timestamp DESC LIMIT $offset, 20 */ $filter = array( 'field' => array('$in' => array(5,6,7)), 'enable' => 1, 'worth' => array('$lt' => 5) ); $cursor = $collection->find($filter); $cursor->sort(array('timestamp' => -1))->skip($offset)->limit(20); foreach ($cursor as $result) { var dump($result); } @crodas - http://crodas.org/ - L EX AT 17
  • 18. Designing data structure Simple multi-blog system @crodas - http://crodas.org/ - L EX AT 18
  • 19. MongoDB - Collections Blog Post User Comment @crodas - http://crodas.org/ - L EX AT 19
  • 20. Blog document $blog = array( "user" => <userref>, "title" => "Foo bar blog" "url" => array( "foobar.foobar.com", "anotherfoo.foobar.com", ), "permissions" => array( "edit" => array(<userref>, <userref>) ); "post" => 1, ... ); @crodas - http://crodas.org/ - L EX AT 20
  • 21. Post document $post = array( "blog" => <blogref>, "author" => <userref>, "uri" => "/another-post", "title" => "Another post", "excerpt" => "bla, bla, bla", "body" => "bar, foo bar, foo, bar", "tags" => array("list", "of tags"), "published" => true, "date" => <mongodate>, ); @crodas - http://crodas.org/ - L EX AT 21
  • 22. Missing docs. $comment = array( "post" => <postref>, "name" => "foobar", "email" => "foo@bar.com", "comment" => "Hello world", "date" => <mongodate>, ); $user = array( "user" => "crodas", "email" => "crodas@php.net", "password" => "a1bad96dc68f891ca887d50eb3fb65ec82123d05", "name" => "Cesar Rodas", ); @crodas - http://crodas.org/ - L EX AT 22
  • 23. About indexes $blog col->ensureIndex(array("url" => 1)); $post col->ensureIndex(array("blog" => 1, "date" => -1)); $post col->ensureIndex(array("blog" => 1, "uri" => 1), array("unique" => 1)); $comment col->ensureIndex(array("post" => 1, "date" => -1)); $user col->ensureIndex(array("user" => 1), array("unique" => 1)); $user col->ensureIndex(array("email" => 1), array("unique" => 1)); @crodas - http://crodas.org/ - L EX AT 23
  • 24. That's it. @crodas - http://crodas.org/ - L EX AT 24
  • 26. Until now, nothing new @crodas - http://crodas.org/ - L EX AT 26
  • 27. Let's shard it! @crodas - http://crodas.org/ - L EX AT 27
  • 28. Strategy Shard Blog collection Shard User collection Other collections are isolated • Create namespaces for post and comments (foo.post, foo.comments) • Modify Blog collection, add info about "namespace" (and DB). MongoDB will distribute our DB and namespaces @crodas - http://crodas.org/ - L EX AT 28
  • 29. Configuring the sharding /* Assuming you have already MongoDB running * on a sharded env., you should do this once. * * $admin is a connection to the "admin" DB. */ $admin->command(array( "shardcollection" => "blog", "key" => array("uri" => 1), )); $admin->command(array( "shardcollection" => "user", "key" => array("user" => 1), "unique" => true, )); @crodas - http://crodas.org/ - L EX AT 29
  • 30. New blog document $blog = array( "user" => <userref>, "title" => "Foo bar blog" "url" => array( "foobar.foobar.com", "anotherfoo.foobar.com", ), "permissions" => array( "edit" => array(<userref>, <userref>) ); "post" => 1, "namespace" => "3h3g3k3", "database" => "34fs321", ); @crodas - http://crodas.org/ - L EX AT 30
  • 31. Select the DB and namespace to use "post" and "comments" @crodas - http://crodas.org/ - L EX AT 31
  • 33. Thank you hackers! @crodas - http://crodas.org/ - L EX AT 33
  • 34. MongoDB is looking from Brazilian help. @crodas - http://crodas.org/ - L EX AT 34
  • 35. @crodas crodas.org @crodas - http://crodas.org/ - L EX AT 35