SlideShare ist ein Scribd-Unternehmen logo
1 von 35
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

[제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
 

Was ist angesagt? (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
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
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 

Kürzlich hochgeladen (20)

Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
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
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 

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