SlideShare une entreprise Scribd logo
1  sur  35
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

[제1회 루씬 한글분석기 기술세미나] solr로 나만의 검색엔진을 만들어보자
[제1회 루씬 한글분석기 기술세미나] solr로 나만의 검색엔진을 만들어보자[제1회 루씬 한글분석기 기술세미나] solr로 나만의 검색엔진을 만들어보자
[제1회 루씬 한글분석기 기술세미나] solr로 나만의 검색엔진을 만들어보자Donghyeok Kang
 
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 PipelinesMongoDB
 
On secure application of PHP wrappers
On secure application  of PHP wrappersOn secure application  of PHP wrappers
On secure application of PHP wrappersPositive Hack Days
 
MongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with MorphiaMongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with MorphiaScott 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 MorphiaMongoDB
 
Java development with MongoDB
Java development with MongoDBJava development with MongoDB
Java development with MongoDBJames 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 АuerYandex
 
MongoDB Europe 2016 - Debugging MongoDB Performance
MongoDB Europe 2016 - Debugging MongoDB PerformanceMongoDB Europe 2016 - Debugging MongoDB Performance
MongoDB Europe 2016 - Debugging MongoDB PerformanceMongoDB
 
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 FrameworkMongoDB
 
Fazendo mágica com ElasticSearch
Fazendo mágica com ElasticSearchFazendo mágica com ElasticSearch
Fazendo mágica com ElasticSearchPedro Franceschi
 
"Solr Update" at code4lib '13 - Chicago
"Solr Update" at code4lib '13 - Chicago"Solr Update" at code4lib '13 - Chicago
"Solr Update" at code4lib '13 - ChicagoErik Hatcher
 
Использование 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 MorphiaMongoDB
 
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 HarlNETWAYS
 

Tendances (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
 

Similaire à MongoDB Advanced Topics

Thinking in documents
Thinking in documentsThinking in documents
Thinking in documentsCésar Rodas
 
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 ClojureDmitry Buzdin
 
はじめてのMongoDB
はじめてのMongoDBはじめてのMongoDB
はじめてのMongoDBTakahiro 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 2012sullis
 
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 DrupalDoug Green
 
Introduction to Elasticsearch
Introduction to ElasticsearchIntroduction to Elasticsearch
Introduction to ElasticsearchSperasoft
 
9b. Document-Oriented Databases lab
9b. Document-Oriented Databases lab9b. Document-Oriented Databases lab
9b. Document-Oriented Databases labFabio Fumarola
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDBantoinegirbal
 
2011 Mongo FR - MongoDB introduction
2011 Mongo FR - MongoDB introduction2011 Mongo FR - MongoDB introduction
2011 Mongo FR - MongoDB introductionantoinegirbal
 
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
 
The Aggregation Framework
The Aggregation FrameworkThe Aggregation Framework
The Aggregation FrameworkMongoDB
 
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 formatForest 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 StrategiesJonathan 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 TeamsMongoDB
 

Similaire à 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
 

Dernier

The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 

Dernier (20)

The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 

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