SlideShare una empresa de Scribd logo
1 de 36
Descargar para leer sin conexión
PHP & MongoDB
Shaken, not stirred
Spyros Passas / @spassas
Friday, April 12, 13
NoSQL | Everybody is talking about it!
Friday, April 12, 13
NoSQL | What
• NoSQL ≠ SQL is dead
• Not an opposite, but an alternative/complement to SQL (Not Only SQL)
• Came as a need for large volumes of data and high transaction rates
• Are generally based on key/value store
• Are very happy with denormalized data since they have no joins
Friday, April 12, 13
NoSQL | Why
• Flexible Data Model, so no prototyping is needed
• Scaling out instead of Scaling up
• Performance is significantly higher
• Cheaper licenses (or free)
• Runs on commodity hardware
• Caching layer already there
• Data variety
Friday, April 12, 13
NoSQL | Why not
• well, it’s not all ACID...
• Less mature than the relational systems (so the ecosystem of tools/addons
is still small)
• BI & Reporting is limited
• Coarse grained Security settings
Friday, April 12, 13
NoSQL | Which
• Key/Value stores
• Document Databases
• And more...
Friday, April 12, 13
MongoDB | Documents & Collections
• Document is the equivalent of an SQL table row and is a set of key/value
pairs
• Collection is the equivalent of an SQL table and is a set of documents not
necessarily of the same type
• Database is the equivalent of a... database
{
“name” : “Spyros Passas”,
“company” : “Neybox”
}
{
“name” : “Spyros Passas”,
“company” : “Neybox”
}
{
“Event” : “JoomlaFrappe”,
“location” : “Athens”
}
Friday, April 12, 13
MongoDB | What can a value be?
• Keys are always strings (without . and $)
• Value can be
• String
• Number
• Date
• Array
• Document
{“name” : “Spyros Passas”}
{“age” : 30}
{“birthday” : Date(“1982-12-12”}
{“interests” : [“Programming”, “NoSQL”]}
{“address” : {
“street” : “123 Pireus st.”,
“city” : “Athens”,
“zip_code” : 17121
}
}
Friday, April 12, 13
MongoDB | Example of a document
{
“_id” : ObjectId(“47cc67093475061e3d95369d”),
“name” : “Spyros Passas”,
“birthday” : Date(“1982-12-12”),
“age” : 30,
“interests” : [“Programming”, “NoSQL”],
“address” : {
“street” : “123 Pireus st.”,
“city” : “Athens”,
“zip_code” : 17121
}
“_id” : ObjectId(“47cc67093475061e3d95369d”)
ObjectId is a special type
Friday, April 12, 13
MongoDB | Indexes
• Any field can be indexed
• Indexes are ordered
• Indexes can be unique
• Compound indexes are possible (and in fact very useful)
• Can be created or dropped at anytime
• Indexes have a large size and an insertion overhead
Friday, April 12, 13
MongoDB | Operators & Modifiers
• Comparison: $lt (<), $lte (<=), $ne (!=), $gte (>=), $gt (>)
• Logical: $and, $or, $not, $nor
• Array: $all, $in, $nin
• Geospatial: $geoWithin, $geoIntersects, $near, $nearSphere
• Fields: $inc, $rename, $set, $unset
• Array: $pop, $pull, $push, $addToSet
Friday, April 12, 13
MongoDB | Data Relations
• MongoDB has no joins (but you can fake them in the application level)
• MongoDB supports nested data (and it’s a pretty good idea actually!)
• Collections are not necessary, but greatly help data organization and
performance
Friday, April 12, 13
MongoDB | Going from relational to NoSQL
• Rethink your data and select a proper database
• Rethink the relationships between your data
• Rethink your query access patterns to create efficient indexes
• Get to know your NoSQL database (and its limitations)
• Move logic from data to application layer (but be careful)
Friday, April 12, 13
MongoDB | Deployment
Mongo Server
Data Layer
Application Layer
App Server + mongos
Friday, April 12, 13
MongoDB | Deployment
Mongo Server
Friday, April 12, 13
MongoDB | Replica Set
Primary (Master)
Secondary (Slave)
Friday, April 12, 13
MongoDB | Replica Set
Primary (Master)
Secondary (Slave)Secondary (Slave) Secondary (Slave)
Friday, April 12, 13
MongoDB | Replica Set when things go wrong
Primary (Master)
Secondary (Slave)Secondary (Slave) Secondary (Slave)
Friday, April 12, 13
MongoDB | Replica Set when things go wrong
Primary (Master)
Secondary (Slave) Secondary (Slave)
Friday, April 12, 13
MongoDB | Replica Set when things go wrong
Primary (Master)
Secondary (Slave) Secondary (Slave)Secondary (Slave)
Friday, April 12, 13
MongoDB | Replica set tips
• Physical machines should be in independent availability zones
• Selecting to read from slaves significantly increases performance (but you
have to be cautious)
Friday, April 12, 13
MongoDB | Sharding
A...Z
Friday, April 12, 13
MongoDB | Sharding
A...J K....P Q....Z
Friday, April 12, 13
MongoDB | Sharding with replica sets
A...J K....P Q....Z
Replica SetReplica SetReplica Set
Friday, April 12, 13
MongoDB | Sharding with replica sets
A...J K....P Q....Z
Config Servers
Replica SetReplica SetReplica Set
Friday, April 12, 13
MongoDB | Things to consider when sharding
• Picking the right sharding key is of paramount importance!
• Rule of thumb:“the shard key must distribute reads and writes and keep the
data you’re using together”
• Key must be of high cardinality
• Key must not be monotonically ascending to infinity
• Key must not be random
• A good idea is a coarsely ascending field + a field you query a lot
Friday, April 12, 13
MongoDB | PHP | The driver
• Serializes objects to BSON
• Uses exceptions to handle errors
• Core classes
• MongoClient: Creates and manages DB connections
• MongoDB: Interact with a database
• MongoCollection: Represents and manages a collection
• MongoCursor: Used to iterate through query results
Friday, April 12, 13
MongoDB | PHP | MongoClient
<?php
// Gets the client
$mongo = new MongoClient(“mongodb://localhost:27017”);
// Sets the read preferences (Primary only or primary & secondary)
$mongo->setReadPreference(MongoClient::RP_SECONDARY);
// If in replica set, returns hosts status
$hosts_array = mongo->getHosts();
// Returns an array with the database names
$db_array = $mongo->listDBs();
// Returns a MongoDB object
$database = $mongo->selectDB(“myblog”);
?>
Creates a connection and sets read preferences
Provide info about hosts status and health
Lists, selects or drops databases
Friday, April 12, 13
MongoDB | PHP | MongoDB
<?php
// Create a collection
$database->createCollection(“blogposts”);
// Select a collection
$blogCollection = $database->selectCollection(“blogposts”);
// Drop a collection
$database->dropCollection(“blogposts”)
?>
Handles Collections
Friday, April 12, 13
MongoDB | PHP | MongoCollection | Insert
<?php
// Fire and forget insertion
$properties = array(“author”=>”spassas”, “title”=>”Hello World”);
$collection->insert($properties);
?>
Insert
<?php
// Safe insertion
$properties = array(“author”=>”spassas”, “title”=>”Hello World”);
$collection->insert($properties, array(“safe”=>true));
?>
Friday, April 12, 13
MongoDB | PHP | MongoCollection | Update
<?php
// Update
$c->insert(array("firstname" => "Spyros", "lastname" => "Passas" ));
$newdata = array('$set' => array("address" => "123 Pireos st"));
$c->update(array("firstname" => "Spyros"), $newdata);
// Upsert
$c->update(
    array("uri" => "/summer_pics"),
    array('$inc' => array("page_hits" => 1)),
    array("upsert" => true)
);
?>
Friday, April 12, 13
MongoDB | PHP | MongoCollection | Delete
<?php
// Delete parameters
$keyValue = array(“name” => “Spyros”);
// Safe remove
$collection->remove($keyValue, array('safe' => true));
// Fire and forget remove
$collection->remove($keyValue);
?>
Friday, April 12, 13
MongoDB | PHP | MongoCollection | Query
<?php
// Get the collection
$posts = $mongo->selectDB(“blog”)->selectCollection(“posts”);
// Find one
$post = $posts->findOne(array('author' => 'john'), array('title'));
// Find many
$allPosts = $posts->find(array('author' => 'john'));
// Find using operators
$commentedPosts = $posts->find(array(‘comment_count’ => array(‘$gt’=>1)));
// Find in arrays
$tags = array(‘technology’, ‘nosql’);
// Find any
$postsWithAnyTag = $posts->find(array('tags' => array('$in' => $tags)));
// Find all
$postsWithAllTags = $posts->find(array('tags' => array('$all' => $tags)));
?>
Friday, April 12, 13
MongoDB | PHP | MongoCursor
<?php
// Iterate through results
$results = $collection->find();
foreach ($results as $result) {
    // Do something here
}
// Sort
$posts = $posts->sort(array('created_at'=> -1));
// Skip a number of results
$posts = $posts->skip(5);
// Limit the number of results
$posts = $posts->limit(10);
// Chaining
$posts->sort(array('created_at'=> -1))->skip(5)->limit(10);
?>
Friday, April 12, 13
MongoDB | PHP | Query monitoring & Optimization
explain()
Gives data about index performance for a specific query
{
"n" : <num>, /* Number documents that match the query */
"nscannedObjects" : <num>, /* total number of documents scanned during
the query */
"nscanned" : <num>, /* total number of documents and index entries */
"millis" : <num>, /* time to complete the query in milliseconds */
“millisShardTotal” : <num> /* total time to complete the query on shards
*/
“millisShardAvg” : <num> /* average time to complete the query on each
shard */
}
Friday, April 12, 13
Thank you!
{“status” : “over and out”,
“mood” : “:)”,
“coming_up” : “Q & A”
“contact_details”: {
“email”:“sp@neybox.com”,
“twitter”:”@spassas”,
}
}
Friday, April 12, 13

Más contenido relacionado

La actualidad más candente

elasticsearch - advanced features in practice
elasticsearch - advanced features in practiceelasticsearch - advanced features in practice
elasticsearch - advanced features in practiceJano Suchal
 
Elasticsearch (Rubyshift 2013)
Elasticsearch (Rubyshift 2013)Elasticsearch (Rubyshift 2013)
Elasticsearch (Rubyshift 2013)Karel Minarik
 
dataviz on d3.js + elasticsearch
dataviz on d3.js + elasticsearchdataviz on d3.js + elasticsearch
dataviz on d3.js + elasticsearchMathieu Elie
 
Hands On Spring Data
Hands On Spring DataHands On Spring Data
Hands On Spring DataEric Bottard
 
Elastic search apache_solr
Elastic search apache_solrElastic search apache_solr
Elastic search apache_solrmacrochen
 
ElasticSearch - index server used as a document database
ElasticSearch - index server used as a document databaseElasticSearch - index server used as a document database
ElasticSearch - index server used as a document databaseRobert Lujo
 
Elastic search Walkthrough
Elastic search WalkthroughElastic search Walkthrough
Elastic search WalkthroughSuhel Meman
 
Elastic Search
Elastic SearchElastic Search
Elastic SearchNavule Rao
 
Elasticsearch first-steps
Elasticsearch first-stepsElasticsearch first-steps
Elasticsearch first-stepsMatteo Moci
 
Elasticsearch: You know, for search! and more!
Elasticsearch: You know, for search! and more!Elasticsearch: You know, for search! and more!
Elasticsearch: You know, for search! and more!Philips Kokoh Prasetyo
 
Managing Your Content with Elasticsearch
Managing Your Content with ElasticsearchManaging Your Content with Elasticsearch
Managing Your Content with ElasticsearchSamantha Quiñones
 
An Introduction to Elastic Search.
An Introduction to Elastic Search.An Introduction to Elastic Search.
An Introduction to Elastic Search.Jurriaan Persyn
 
Philly PHP: April '17 Elastic Search Introduction by Aditya Bhamidpati
Philly PHP: April '17 Elastic Search Introduction by Aditya BhamidpatiPhilly PHP: April '17 Elastic Search Introduction by Aditya Bhamidpati
Philly PHP: April '17 Elastic Search Introduction by Aditya BhamidpatiRobert Calcavecchia
 
NoSQL: Why, When, and How
NoSQL: Why, When, and HowNoSQL: Why, When, and How
NoSQL: Why, When, and HowBigBlueHat
 
Introduction to Lucene & Solr and Usecases
Introduction to Lucene & Solr and UsecasesIntroduction to Lucene & Solr and Usecases
Introduction to Lucene & Solr and UsecasesRahul Jain
 
DataFrame: Spark's new abstraction for data science by Reynold Xin of Databricks
DataFrame: Spark's new abstraction for data science by Reynold Xin of DatabricksDataFrame: Spark's new abstraction for data science by Reynold Xin of Databricks
DataFrame: Spark's new abstraction for data science by Reynold Xin of DatabricksData Con LA
 
Distributed percolator in elasticsearch
Distributed percolator in elasticsearchDistributed percolator in elasticsearch
Distributed percolator in elasticsearchmartijnvg
 
Introduction to Elasticsearch
Introduction to ElasticsearchIntroduction to Elasticsearch
Introduction to ElasticsearchJason Austin
 

La actualidad más candente (20)

elasticsearch - advanced features in practice
elasticsearch - advanced features in practiceelasticsearch - advanced features in practice
elasticsearch - advanced features in practice
 
Elasticsearch (Rubyshift 2013)
Elasticsearch (Rubyshift 2013)Elasticsearch (Rubyshift 2013)
Elasticsearch (Rubyshift 2013)
 
dataviz on d3.js + elasticsearch
dataviz on d3.js + elasticsearchdataviz on d3.js + elasticsearch
dataviz on d3.js + elasticsearch
 
Hands On Spring Data
Hands On Spring DataHands On Spring Data
Hands On Spring Data
 
Elastic search apache_solr
Elastic search apache_solrElastic search apache_solr
Elastic search apache_solr
 
ElasticSearch - index server used as a document database
ElasticSearch - index server used as a document databaseElasticSearch - index server used as a document database
ElasticSearch - index server used as a document database
 
Elastic search Walkthrough
Elastic search WalkthroughElastic search Walkthrough
Elastic search Walkthrough
 
Elastic Search
Elastic SearchElastic Search
Elastic Search
 
Elasticsearch first-steps
Elasticsearch first-stepsElasticsearch first-steps
Elasticsearch first-steps
 
Elasticsearch: You know, for search! and more!
Elasticsearch: You know, for search! and more!Elasticsearch: You know, for search! and more!
Elasticsearch: You know, for search! and more!
 
Managing Your Content with Elasticsearch
Managing Your Content with ElasticsearchManaging Your Content with Elasticsearch
Managing Your Content with Elasticsearch
 
Elastic Search
Elastic SearchElastic Search
Elastic Search
 
An Introduction to Elastic Search.
An Introduction to Elastic Search.An Introduction to Elastic Search.
An Introduction to Elastic Search.
 
Philly PHP: April '17 Elastic Search Introduction by Aditya Bhamidpati
Philly PHP: April '17 Elastic Search Introduction by Aditya BhamidpatiPhilly PHP: April '17 Elastic Search Introduction by Aditya Bhamidpati
Philly PHP: April '17 Elastic Search Introduction by Aditya Bhamidpati
 
NoSQL: Why, When, and How
NoSQL: Why, When, and HowNoSQL: Why, When, and How
NoSQL: Why, When, and How
 
Elasticsearch Introduction at BigData meetup
Elasticsearch Introduction at BigData meetupElasticsearch Introduction at BigData meetup
Elasticsearch Introduction at BigData meetup
 
Introduction to Lucene & Solr and Usecases
Introduction to Lucene & Solr and UsecasesIntroduction to Lucene & Solr and Usecases
Introduction to Lucene & Solr and Usecases
 
DataFrame: Spark's new abstraction for data science by Reynold Xin of Databricks
DataFrame: Spark's new abstraction for data science by Reynold Xin of DatabricksDataFrame: Spark's new abstraction for data science by Reynold Xin of Databricks
DataFrame: Spark's new abstraction for data science by Reynold Xin of Databricks
 
Distributed percolator in elasticsearch
Distributed percolator in elasticsearchDistributed percolator in elasticsearch
Distributed percolator in elasticsearch
 
Introduction to Elasticsearch
Introduction to ElasticsearchIntroduction to Elasticsearch
Introduction to Elasticsearch
 

Destacado

Project sample- PHP, MySQL, Android, MongoDB, R
Project sample- PHP, MySQL, Android, MongoDB, RProject sample- PHP, MySQL, Android, MongoDB, R
Project sample- PHP, MySQL, Android, MongoDB, RVijayananda Mohire
 
Open Source Creativity
Open Source CreativityOpen Source Creativity
Open Source CreativitySara Cannon
 
The impact of innovation on travel and tourism industries (World Travel Marke...
The impact of innovation on travel and tourism industries (World Travel Marke...The impact of innovation on travel and tourism industries (World Travel Marke...
The impact of innovation on travel and tourism industries (World Travel Marke...Brian Solis
 
Reuters: Pictures of the Year 2016 (Part 2)
Reuters: Pictures of the Year 2016 (Part 2)Reuters: Pictures of the Year 2016 (Part 2)
Reuters: Pictures of the Year 2016 (Part 2)maditabalnco
 
The Six Highest Performing B2B Blog Post Formats
The Six Highest Performing B2B Blog Post FormatsThe Six Highest Performing B2B Blog Post Formats
The Six Highest Performing B2B Blog Post FormatsBarry Feldman
 
The Outcome Economy
The Outcome EconomyThe Outcome Economy
The Outcome EconomyHelge Tennø
 

Destacado (6)

Project sample- PHP, MySQL, Android, MongoDB, R
Project sample- PHP, MySQL, Android, MongoDB, RProject sample- PHP, MySQL, Android, MongoDB, R
Project sample- PHP, MySQL, Android, MongoDB, R
 
Open Source Creativity
Open Source CreativityOpen Source Creativity
Open Source Creativity
 
The impact of innovation on travel and tourism industries (World Travel Marke...
The impact of innovation on travel and tourism industries (World Travel Marke...The impact of innovation on travel and tourism industries (World Travel Marke...
The impact of innovation on travel and tourism industries (World Travel Marke...
 
Reuters: Pictures of the Year 2016 (Part 2)
Reuters: Pictures of the Year 2016 (Part 2)Reuters: Pictures of the Year 2016 (Part 2)
Reuters: Pictures of the Year 2016 (Part 2)
 
The Six Highest Performing B2B Blog Post Formats
The Six Highest Performing B2B Blog Post FormatsThe Six Highest Performing B2B Blog Post Formats
The Six Highest Performing B2B Blog Post Formats
 
The Outcome Economy
The Outcome EconomyThe Outcome Economy
The Outcome Economy
 

Similar a Mongo db php_shaken_not_stirred_joomlafrappe

Intro To Mongo Db
Intro To Mongo DbIntro To Mongo Db
Intro To Mongo Dbchriskite
 
Introduction to MongoDB and Workshop
Introduction to MongoDB and WorkshopIntroduction to MongoDB and Workshop
Introduction to MongoDB and WorkshopAhmedabadJavaMeetup
 
Mongo Presentation by Metatagg Solutions
Mongo Presentation by Metatagg SolutionsMongo Presentation by Metatagg Solutions
Mongo Presentation by Metatagg SolutionsMetatagg Solutions
 
How to use NoSQL in Enterprise Java Applications - NoSQL Roadshow Basel
How to use NoSQL in Enterprise Java Applications - NoSQL Roadshow BaselHow to use NoSQL in Enterprise Java Applications - NoSQL Roadshow Basel
How to use NoSQL in Enterprise Java Applications - NoSQL Roadshow BaselPatrick Baumgartner
 
Getting Started with MongoDB (TCF ITPC 2014)
Getting Started with MongoDB (TCF ITPC 2014)Getting Started with MongoDB (TCF ITPC 2014)
Getting Started with MongoDB (TCF ITPC 2014)Michael Redlich
 
Tech Gupshup Meetup On MongoDB - 24/06/2016
Tech Gupshup Meetup On MongoDB - 24/06/2016Tech Gupshup Meetup On MongoDB - 24/06/2016
Tech Gupshup Meetup On MongoDB - 24/06/2016Mukesh Tilokani
 
Data Abstraction for Large Web Applications
Data Abstraction for Large Web ApplicationsData Abstraction for Large Web Applications
Data Abstraction for Large Web Applicationsbrandonsavage
 
Introduction to NoSQL with MongoDB
Introduction to NoSQL with MongoDBIntroduction to NoSQL with MongoDB
Introduction to NoSQL with MongoDBHector Correa
 
Architecture | Busy Java Developers Guide to NoSQL | Ted Neward
Architecture | Busy Java Developers Guide to NoSQL | Ted NewardArchitecture | Busy Java Developers Guide to NoSQL | Ted Neward
Architecture | Busy Java Developers Guide to NoSQL | Ted NewardJAX London
 
Mongodb intro
Mongodb introMongodb intro
Mongodb introchristkv
 
Slick Data Sharding: Slides from DrupalCon London
Slick Data Sharding: Slides from DrupalCon LondonSlick Data Sharding: Slides from DrupalCon London
Slick Data Sharding: Slides from DrupalCon LondonPhase2
 
An Introduction To NoSQL & MongoDB
An Introduction To NoSQL & MongoDBAn Introduction To NoSQL & MongoDB
An Introduction To NoSQL & MongoDBLee Theobald
 
Use Your MySQL Knowledge to Become a MongoDB Guru
Use Your MySQL Knowledge to Become a MongoDB GuruUse Your MySQL Knowledge to Become a MongoDB Guru
Use Your MySQL Knowledge to Become a MongoDB GuruTim Callaghan
 
Introducción a NoSQL
Introducción a NoSQLIntroducción a NoSQL
Introducción a NoSQLMongoDB
 
Your Database Cannot Do this (well)
Your Database Cannot Do this (well)Your Database Cannot Do this (well)
Your Database Cannot Do this (well)javier ramirez
 
Using Document Databases with TYPO3 Flow
Using Document Databases with TYPO3 FlowUsing Document Databases with TYPO3 Flow
Using Document Databases with TYPO3 FlowKarsten Dambekalns
 
MongoDB Pros and Cons
MongoDB Pros and ConsMongoDB Pros and Cons
MongoDB Pros and Consjohnrjenson
 

Similar a Mongo db php_shaken_not_stirred_joomlafrappe (20)

Intro To Mongo Db
Intro To Mongo DbIntro To Mongo Db
Intro To Mongo Db
 
Introduction to MongoDB and Workshop
Introduction to MongoDB and WorkshopIntroduction to MongoDB and Workshop
Introduction to MongoDB and Workshop
 
Mongo Presentation by Metatagg Solutions
Mongo Presentation by Metatagg SolutionsMongo Presentation by Metatagg Solutions
Mongo Presentation by Metatagg Solutions
 
How to use NoSQL in Enterprise Java Applications - NoSQL Roadshow Basel
How to use NoSQL in Enterprise Java Applications - NoSQL Roadshow BaselHow to use NoSQL in Enterprise Java Applications - NoSQL Roadshow Basel
How to use NoSQL in Enterprise Java Applications - NoSQL Roadshow Basel
 
elasticsearch
elasticsearchelasticsearch
elasticsearch
 
Getting Started with MongoDB (TCF ITPC 2014)
Getting Started with MongoDB (TCF ITPC 2014)Getting Started with MongoDB (TCF ITPC 2014)
Getting Started with MongoDB (TCF ITPC 2014)
 
Tech Gupshup Meetup On MongoDB - 24/06/2016
Tech Gupshup Meetup On MongoDB - 24/06/2016Tech Gupshup Meetup On MongoDB - 24/06/2016
Tech Gupshup Meetup On MongoDB - 24/06/2016
 
MongoDB
MongoDBMongoDB
MongoDB
 
Data Abstraction for Large Web Applications
Data Abstraction for Large Web ApplicationsData Abstraction for Large Web Applications
Data Abstraction for Large Web Applications
 
Introduction to NoSQL with MongoDB
Introduction to NoSQL with MongoDBIntroduction to NoSQL with MongoDB
Introduction to NoSQL with MongoDB
 
Architecture | Busy Java Developers Guide to NoSQL | Ted Neward
Architecture | Busy Java Developers Guide to NoSQL | Ted NewardArchitecture | Busy Java Developers Guide to NoSQL | Ted Neward
Architecture | Busy Java Developers Guide to NoSQL | Ted Neward
 
Mongodb intro
Mongodb introMongodb intro
Mongodb intro
 
Slick Data Sharding: Slides from DrupalCon London
Slick Data Sharding: Slides from DrupalCon LondonSlick Data Sharding: Slides from DrupalCon London
Slick Data Sharding: Slides from DrupalCon London
 
An Introduction To NoSQL & MongoDB
An Introduction To NoSQL & MongoDBAn Introduction To NoSQL & MongoDB
An Introduction To NoSQL & MongoDB
 
Use Your MySQL Knowledge to Become a MongoDB Guru
Use Your MySQL Knowledge to Become a MongoDB GuruUse Your MySQL Knowledge to Become a MongoDB Guru
Use Your MySQL Knowledge to Become a MongoDB Guru
 
Introducción a NoSQL
Introducción a NoSQLIntroducción a NoSQL
Introducción a NoSQL
 
Your Database Cannot Do this (well)
Your Database Cannot Do this (well)Your Database Cannot Do this (well)
Your Database Cannot Do this (well)
 
Using Document Databases with TYPO3 Flow
Using Document Databases with TYPO3 FlowUsing Document Databases with TYPO3 Flow
Using Document Databases with TYPO3 Flow
 
Rails with mongodb
Rails with mongodbRails with mongodb
Rails with mongodb
 
MongoDB Pros and Cons
MongoDB Pros and ConsMongoDB Pros and Cons
MongoDB Pros and Cons
 

Último

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 

Último (20)

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 

Mongo db php_shaken_not_stirred_joomlafrappe

  • 1. PHP & MongoDB Shaken, not stirred Spyros Passas / @spassas Friday, April 12, 13
  • 2. NoSQL | Everybody is talking about it! Friday, April 12, 13
  • 3. NoSQL | What • NoSQL ≠ SQL is dead • Not an opposite, but an alternative/complement to SQL (Not Only SQL) • Came as a need for large volumes of data and high transaction rates • Are generally based on key/value store • Are very happy with denormalized data since they have no joins Friday, April 12, 13
  • 4. NoSQL | Why • Flexible Data Model, so no prototyping is needed • Scaling out instead of Scaling up • Performance is significantly higher • Cheaper licenses (or free) • Runs on commodity hardware • Caching layer already there • Data variety Friday, April 12, 13
  • 5. NoSQL | Why not • well, it’s not all ACID... • Less mature than the relational systems (so the ecosystem of tools/addons is still small) • BI & Reporting is limited • Coarse grained Security settings Friday, April 12, 13
  • 6. NoSQL | Which • Key/Value stores • Document Databases • And more... Friday, April 12, 13
  • 7. MongoDB | Documents & Collections • Document is the equivalent of an SQL table row and is a set of key/value pairs • Collection is the equivalent of an SQL table and is a set of documents not necessarily of the same type • Database is the equivalent of a... database { “name” : “Spyros Passas”, “company” : “Neybox” } { “name” : “Spyros Passas”, “company” : “Neybox” } { “Event” : “JoomlaFrappe”, “location” : “Athens” } Friday, April 12, 13
  • 8. MongoDB | What can a value be? • Keys are always strings (without . and $) • Value can be • String • Number • Date • Array • Document {“name” : “Spyros Passas”} {“age” : 30} {“birthday” : Date(“1982-12-12”} {“interests” : [“Programming”, “NoSQL”]} {“address” : { “street” : “123 Pireus st.”, “city” : “Athens”, “zip_code” : 17121 } } Friday, April 12, 13
  • 9. MongoDB | Example of a document { “_id” : ObjectId(“47cc67093475061e3d95369d”), “name” : “Spyros Passas”, “birthday” : Date(“1982-12-12”), “age” : 30, “interests” : [“Programming”, “NoSQL”], “address” : { “street” : “123 Pireus st.”, “city” : “Athens”, “zip_code” : 17121 } “_id” : ObjectId(“47cc67093475061e3d95369d”) ObjectId is a special type Friday, April 12, 13
  • 10. MongoDB | Indexes • Any field can be indexed • Indexes are ordered • Indexes can be unique • Compound indexes are possible (and in fact very useful) • Can be created or dropped at anytime • Indexes have a large size and an insertion overhead Friday, April 12, 13
  • 11. MongoDB | Operators & Modifiers • Comparison: $lt (<), $lte (<=), $ne (!=), $gte (>=), $gt (>) • Logical: $and, $or, $not, $nor • Array: $all, $in, $nin • Geospatial: $geoWithin, $geoIntersects, $near, $nearSphere • Fields: $inc, $rename, $set, $unset • Array: $pop, $pull, $push, $addToSet Friday, April 12, 13
  • 12. MongoDB | Data Relations • MongoDB has no joins (but you can fake them in the application level) • MongoDB supports nested data (and it’s a pretty good idea actually!) • Collections are not necessary, but greatly help data organization and performance Friday, April 12, 13
  • 13. MongoDB | Going from relational to NoSQL • Rethink your data and select a proper database • Rethink the relationships between your data • Rethink your query access patterns to create efficient indexes • Get to know your NoSQL database (and its limitations) • Move logic from data to application layer (but be careful) Friday, April 12, 13
  • 14. MongoDB | Deployment Mongo Server Data Layer Application Layer App Server + mongos Friday, April 12, 13
  • 15. MongoDB | Deployment Mongo Server Friday, April 12, 13
  • 16. MongoDB | Replica Set Primary (Master) Secondary (Slave) Friday, April 12, 13
  • 17. MongoDB | Replica Set Primary (Master) Secondary (Slave)Secondary (Slave) Secondary (Slave) Friday, April 12, 13
  • 18. MongoDB | Replica Set when things go wrong Primary (Master) Secondary (Slave)Secondary (Slave) Secondary (Slave) Friday, April 12, 13
  • 19. MongoDB | Replica Set when things go wrong Primary (Master) Secondary (Slave) Secondary (Slave) Friday, April 12, 13
  • 20. MongoDB | Replica Set when things go wrong Primary (Master) Secondary (Slave) Secondary (Slave)Secondary (Slave) Friday, April 12, 13
  • 21. MongoDB | Replica set tips • Physical machines should be in independent availability zones • Selecting to read from slaves significantly increases performance (but you have to be cautious) Friday, April 12, 13
  • 23. MongoDB | Sharding A...J K....P Q....Z Friday, April 12, 13
  • 24. MongoDB | Sharding with replica sets A...J K....P Q....Z Replica SetReplica SetReplica Set Friday, April 12, 13
  • 25. MongoDB | Sharding with replica sets A...J K....P Q....Z Config Servers Replica SetReplica SetReplica Set Friday, April 12, 13
  • 26. MongoDB | Things to consider when sharding • Picking the right sharding key is of paramount importance! • Rule of thumb:“the shard key must distribute reads and writes and keep the data you’re using together” • Key must be of high cardinality • Key must not be monotonically ascending to infinity • Key must not be random • A good idea is a coarsely ascending field + a field you query a lot Friday, April 12, 13
  • 27. MongoDB | PHP | The driver • Serializes objects to BSON • Uses exceptions to handle errors • Core classes • MongoClient: Creates and manages DB connections • MongoDB: Interact with a database • MongoCollection: Represents and manages a collection • MongoCursor: Used to iterate through query results Friday, April 12, 13
  • 28. MongoDB | PHP | MongoClient <?php // Gets the client $mongo = new MongoClient(“mongodb://localhost:27017”); // Sets the read preferences (Primary only or primary & secondary) $mongo->setReadPreference(MongoClient::RP_SECONDARY); // If in replica set, returns hosts status $hosts_array = mongo->getHosts(); // Returns an array with the database names $db_array = $mongo->listDBs(); // Returns a MongoDB object $database = $mongo->selectDB(“myblog”); ?> Creates a connection and sets read preferences Provide info about hosts status and health Lists, selects or drops databases Friday, April 12, 13
  • 29. MongoDB | PHP | MongoDB <?php // Create a collection $database->createCollection(“blogposts”); // Select a collection $blogCollection = $database->selectCollection(“blogposts”); // Drop a collection $database->dropCollection(“blogposts”) ?> Handles Collections Friday, April 12, 13
  • 30. MongoDB | PHP | MongoCollection | Insert <?php // Fire and forget insertion $properties = array(“author”=>”spassas”, “title”=>”Hello World”); $collection->insert($properties); ?> Insert <?php // Safe insertion $properties = array(“author”=>”spassas”, “title”=>”Hello World”); $collection->insert($properties, array(“safe”=>true)); ?> Friday, April 12, 13
  • 31. MongoDB | PHP | MongoCollection | Update <?php // Update $c->insert(array("firstname" => "Spyros", "lastname" => "Passas" )); $newdata = array('$set' => array("address" => "123 Pireos st")); $c->update(array("firstname" => "Spyros"), $newdata); // Upsert $c->update(     array("uri" => "/summer_pics"),     array('$inc' => array("page_hits" => 1)),     array("upsert" => true) ); ?> Friday, April 12, 13
  • 32. MongoDB | PHP | MongoCollection | Delete <?php // Delete parameters $keyValue = array(“name” => “Spyros”); // Safe remove $collection->remove($keyValue, array('safe' => true)); // Fire and forget remove $collection->remove($keyValue); ?> Friday, April 12, 13
  • 33. MongoDB | PHP | MongoCollection | Query <?php // Get the collection $posts = $mongo->selectDB(“blog”)->selectCollection(“posts”); // Find one $post = $posts->findOne(array('author' => 'john'), array('title')); // Find many $allPosts = $posts->find(array('author' => 'john')); // Find using operators $commentedPosts = $posts->find(array(‘comment_count’ => array(‘$gt’=>1))); // Find in arrays $tags = array(‘technology’, ‘nosql’); // Find any $postsWithAnyTag = $posts->find(array('tags' => array('$in' => $tags))); // Find all $postsWithAllTags = $posts->find(array('tags' => array('$all' => $tags))); ?> Friday, April 12, 13
  • 34. MongoDB | PHP | MongoCursor <?php // Iterate through results $results = $collection->find(); foreach ($results as $result) {     // Do something here } // Sort $posts = $posts->sort(array('created_at'=> -1)); // Skip a number of results $posts = $posts->skip(5); // Limit the number of results $posts = $posts->limit(10); // Chaining $posts->sort(array('created_at'=> -1))->skip(5)->limit(10); ?> Friday, April 12, 13
  • 35. MongoDB | PHP | Query monitoring & Optimization explain() Gives data about index performance for a specific query { "n" : <num>, /* Number documents that match the query */ "nscannedObjects" : <num>, /* total number of documents scanned during the query */ "nscanned" : <num>, /* total number of documents and index entries */ "millis" : <num>, /* time to complete the query in milliseconds */ “millisShardTotal” : <num> /* total time to complete the query on shards */ “millisShardAvg” : <num> /* average time to complete the query on each shard */ } Friday, April 12, 13
  • 36. Thank you! {“status” : “over and out”, “mood” : “:)”, “coming_up” : “Q & A” “contact_details”: { “email”:“sp@neybox.com”, “twitter”:”@spassas”, } } Friday, April 12, 13