SlideShare una empresa de Scribd logo
1 de 33
Descargar para leer sin conexión
- By Vijay Thakor
What is MongoDB ?

• MongoDB is an open source document
  database, and the leading NoSQL database.

• MongoDB is a document orinted database that
  provides high performance, high availability, and
  easy scalability.
• It is Maintained and supported by 10gen.
What is NoSQL ?

• NoSQL is a kind of database that, unlike most
  relational databases, does not provide a SQL
  interface to manipulate data.

• NoSQL databases are divided into three
  categories: column-oriented, key-value pairs,
  and document-oriented databases.
What is a document-oriented
            database?

• For this type of databases, a document is a
  data structure that has variable number of
  properties.
• Documents do not have a predefined schema
  like relational database tables. Documents can
  have multiple properties. Documents can also
  be grouped in collections.
The mongoDB PHP extension
•   Maintained and supported by 10gen.
•   Can be installed with pecl: pecl install mongo
•    Add extension=mongo.so to php.ini
•   JSON Document: the data (row)
•   Collection: contains documents (table, view)
•   Index
•   Embedded Document (~join)
Connecting to mongoDb

No tables or collections have to do be explicitly created

<?php
$m = new Mongo();
$database = $m->demo;
$collection = $database->testCollection;
?>

Different connection strings:
● $m = new Mongo("mongodb://localhost");
● $m = new Mongo("localhost:27017");
● $m = new Mongo("mongodb://localhost:29000");
● $m = new Mongo("mongodb://mongo.example.com");
● $m = new Mongo("mongodb://mdb1.example.com,mdb2.example.com");
Select a Database

• If no database exists already, a new database is
  created. Currently there are two ways to do this:
     1. $db = $connection->selectDB('dbname');
     2. $db = $connection->dbname;


• Then it is necessary to select a collection to
  work with, like we would pick a table to work
  with when using relational databases.
     $collection = $db->selectCollection('people');
     or simply
     $collection = $db->people;
Documents

• Stored as BSON (Binary JSON)
• Can have embedded documents
• Have a unique ID (the _id field)
Simple document:
    {
        "_id" : ObjectId("4cb4ab6d7addf98506010001"),
        "id" : NumberLong(1),
        "desc" : "ONE"
    }
Documents

• Document with embedded documents:
{
      "_id" : "derickr","name" : "Derick Rethans",
      "articles" : [
      {
      "title" : "Profiling PHP Applications",
      "url" : "http://derickrethans.nl/talks/profiling-phptourlille11.pdf",
      },
      {
      "title" : "Xdebug",
      "url" : "http://derickrethans.nl/talks/xdebug-phpbcn11.pdf",
      }
] }
Inserting a document
<?php
$document = array(
      "_id" => "derickr",
      "name" => "Derick Rethans",
      "articles" => array(
      array(
      "title" => "Profiling PHP Applications",
      "url" => "http://derickrethans.nl/talks/profiling-phptourlille11.pdf",
), array(
"title" => "Xdebug",
"url" => "http://derickrethans.nl/talks/xdebug-phpbcn11.pdf",
) ) );
$m = new Mongo();
var_dump( $m->demo->articles->insert( $document ) );
?>
mongoDB supports many types
• null
• boolean
• integer (both 32-bit and 64-bit, MongoInt32,
• MongoInt64)
• double
• string (UTF-8)
• array
• associative array
• MongoRegex
• MongoId
• MongoDate
• MongoCode
• MongoBinData
Comparison with mysql
• In Mysql, first we have to create database in phpmyadmin
  and then we have to select database by
      mysql_select_db(‘dbname’);

• Where as in Mongodb no need to create database,
  database is created automatically when using it like
       $mongo = new Mongo();
       $db = $mongo->selectDB(“test”);
  With Authentication:
       $mongo = new Mongo(“mongodb://{$username}:{$password}@{$host}”);
       $db = $mongo->selectDB(“test”);
Comparison with mysql

• In mysql after creating and selecting database we can
  create table as
      CREATE TABLE authors (id INT, name VARCHAR(20), email VARCHAR(20));

• Where as in Mongodb we can create collection(table)
  like
      $mongo = new Mongo();
      $db = $mongo->selectDB(“test”);

      $db->createCollection(“people”,false);
Comparison with mysql
• In mysql, after selecting database we can insert
  data into table with the help of query like
      $query = ‘insert into table_name (‘fields name’) values(‘values’);’
      mysql_query($query);

• Where as in mongoDb we insert data like,
   $people = $db->people;
   $insert = array(“user” => “demo@9lessons.info”, “password” =>
   md5(“demo_password”));
   $db->insert($insert);
  Where people is the collection name.
Comparison with mysql
• In mysql, after selecting database we can Update
  data into table with the help of query like
      $query = ‘UPDATE table_name SET fields name = ‘value’;
      mysql_query($query);

• Where as in mongoDb we Update data like,
   $update = array(“$set” => array(“user” => “demo@9lessons.info”));
   $where = array(“password” => “password”);
   $people->update($where,$update);
  Mongo Shell:
   db.people.update({password:”password”},{$set :
   {user:”demo@demo.com”}});
Comparison with mysql
• Finally we can use select query to select data
  from the table of database like below query in
  mysql,
  $query = ‘select * from table where field_name = ‘value’’;

• Where as in mongoDb we use following query
  to select data from collections
  An empty query document ({}) selects all documents in the collection:
  db.inventory.find( {} )
Comparison with mysql
• A single-clause query selects all documents in
  a collection where a field has a certain value.
  These are simple, “equality” queries.

1. Fetch people by e-mail address:

  $filter = array('email' => 'crodas@php.net');
  $cursor = $collection->find($filter);
  foreach ($cursor as $user) {
  var_dump($user);
  }
Comparison with mysql

2. Fetch people who has more than ten sessions.

  $filter = array('sessions' => array('$gt' => 10));
  $cursor = $collection->find($filter);


  Fetch people that do not have the sessions property set

  $filter = array(
  'sessions' => array('$exists' => false)
  );
  $cursor = $collection->find($filter);
Comparison with mysql
3. Fetch people that have an address in Paraguay and have
   more than 15 sessions

    $filter = array(
    'address.country' => 'PY',
    'sessions' => array('$gt' => 10)
    );
    $cursor = $collection->find($filter);

One important detail worth mentioning is that queries are not executed until
    the result is actually requested. In the first example the query is executed
    when the foreach loop starts.
Comparison with mysql
• Sorting Records
  What if we want to sort records, say by first name or
  nationality? Similar to SQL, Mongo provides the sort
  command. The command, like the find command takes a list
  of options to determine the sort order.
  Unlike SQL, however we specify ascending and descending
  differently. We do that as follows:
       1. Ascending: -1
       2. Descending: 1
• Let’s have a look at an example:
Comparison with mysql
  db.collection.find({gender: 'm', $or: [{nationality: 'english'},
  {nationality: 'american'}]}).sort({nationality: -1});
This example retrieves all male, English or American, actors and
  sorts them in descending order of nationality.
• Limiting Records
  What if we had a pretty big data set (lucky us, we don’t) and we
  wanted to limit the results to just 2? Mongo provides the limit
  command, similar to MySQL and allows us to do just that. Let’s
  update our previous query and return just 2 records. Have a
  look at the following command:
• db.collection.find({gender: 'm', $or: [{nationality: 'english'},
  {nationality: 'american'}]}).limit(2);
Login Example in mongoDb
• Finally it’s time to do small example using
  mongoDb as database, let’s create login process
  with mongoDb.
• First we have to create login form like,
  <form action="index.php" method="POST">
  Email:
  <input type="text" id="usr_email" name="usr_email" />
  Password:
  <input type="password" id="usr_password" name="usr_password" />
  <input name="submitForm" id="submitForm" type="submit" value="Login"/>
  </form>
Login Example in mongoDb
• And the php Process page like,
  <?php
  $succss = "";
  if(isset($_POST) and $_POST['submitForm'] == "Login" )
  {
  $usr_email = mysql_escape_string($_POST['usr_email']);
  $usr_password = mysql_escape_string($_POST['usr_password']);
  $error = array();
  // Email Validation
  if(empty($usr_email) or !filter_var($usr_email,FILTER_SANITIZE_EMAIL))
  {
  $error[] = "Empty or invalid email address";
  }
  if(empty($usr_password)){
  $error[] = "Enter your password";
  }
Login Example in mongoDb
• if(count($error) == 0){
  $con = new Mongo();
  if($con){
  // Select Database
  $db = $con->test;
  // Select Collection
  $people = $db->people;
  $qry = array("user" => $usr_email,"password" => md5($usr_password));
  $result = $people->findOne($qry);
  if($result){
  $success = "You are successully loggedIn";
  // Rest of code up to you....
  }
  } else {
  die("Mongo DB not installed");
  } }}
  ?>
Blog system with mongoDb
lets say you want to build a blog system with users, posts and comments. You
would implement it defining with a table schema like this when using a relational
database.
Blog system with mongoDb
• The equivalent document definition that represents the same structures in
  MongoDB would be defined like this:
•   $users = array(
    'username' => 'crodas',
    'name' => 'Cesar Rodas',
    );
    $posts = array(
    'uri' => '/foo-bar-post',
    'author_id' => $users->_id,
    'title' => 'Foo bar post',
    'summary' => 'This is a summary text',
    'body' => 'This is the body',
    'comments' => array(
      array(
    'name' => 'user',
    'email' => 'foo@bar.com',
    'content' => 'nice post'
    ) ) );
Blog system with mongoDb
• As you may notice, we only need one document to represent both the posts
  and comments. That is because comments are sub-documents of post
  documents.
• This makes the implementation much simpler. It also saves time to query the
  database when you want to access either a post and its comments.
• To make it even more abbreviated, the details of the users making comments
  could be merged with the comment definitions, so you can retrieve either the
  posts, comments and users with a single query.
• $posts = array(
  'uri' => '/foo-bar-post',
   'author_id' => $users->_id,
   'author_name' => 'Cesar Rodas',
   'author_username' => 'crodas',
   'title' => 'Foo bar post',
   'summary' => 'This is a summary text',
Blog system with mongoDb

    'body' => 'This is the body',
    'comments' => array(
     array(
   'name' => 'user',
   'email' => 'foo@bar.com',
   'comment' => 'nice post'
   ),
   )
   );

• This means that some duplicated information may exist, but keep in mind that
  disk space is much cheaper than CPU and RAM, and even more important that
  the time and patience of your site visitors.
Blog system with mongoDb
• If you are concerned with synchronization of duplicated information, you
  can solve that problem by executing this update query when the author
  updates his profile:
• $filter = array(
  'author_id' => $author['_id'],
  );

   $data = array(
   '$set' => array(
    'author_name' => 'Cesar D. Rodas',
   'author_username' => 'cesar',
   )
   );
   $collection->update($filter, $data, array(
   'multiple' => true)
   );
Blog system with mongoDb
• Given these optimizations of our data model, lets rewrite some SQL as
  equivalent queries to MongoDB.

  SELECT * FROM posts
  INNER JOIN users ON users.id = posts.user_id
   WHERE URL = :url;
  SELECT * FROM comments WHERE post_id = $post_id;
• First, add this index just once:

   $collection->ensureIndex(
   array('uri' => 1),
   array('unique' => 1, 'background')
   );

   $collection->find(array('uri' => '<uri>'));
Blog system with mongoDb
• INSERT INTO comments(post_id, name, email, contents)
  VALUES(:post_id, :name, :email, :comment);
• $comment = array(
  'name' => $_POST['name'],
  'email' => $_POST['email'],
  'comment' => $_POST['comment'],
  );

  $filter = array(
  'uri' => $_POST['uri'],
  );

  $collection->update($filter, array(
  '$push' => array('comments' => $comment))
  );
Blog system with mongoDb
• SELECT * FROM posts WHERE id IN (
  SELECT DISTINCT post_id FROM comments WHERE email = :email
  );

  First, add this index just once:

  $collection->ensureIndex(
  array('comments.email' => 1),
  array('background' => 1)
  );
  $collection->find( array('comments.email' => $email) );
Thank You




www.metataggsolutions.com

Más contenido relacionado

La actualidad más candente

MongoDB : The Definitive Guide
MongoDB : The Definitive GuideMongoDB : The Definitive Guide
MongoDB : The Definitive Guide
Wildan Maulana
 
Intro To Mongo Db
Intro To Mongo DbIntro To Mongo Db
Intro To Mongo Db
chriskite
 

La actualidad más candente (20)

Indexing
IndexingIndexing
Indexing
 
Building Apps with MongoDB
Building Apps with MongoDBBuilding Apps with MongoDB
Building Apps with MongoDB
 
Back to Basics Webinar 1: Introduction to NoSQL
Back to Basics Webinar 1: Introduction to NoSQLBack to Basics Webinar 1: Introduction to NoSQL
Back to Basics Webinar 1: Introduction to NoSQL
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
Webinar: Back to Basics: Thinking in Documents
Webinar: Back to Basics: Thinking in DocumentsWebinar: Back to Basics: Thinking in Documents
Webinar: Back to Basics: Thinking in Documents
 
MongoDB for Beginners
MongoDB for BeginnersMongoDB for Beginners
MongoDB for Beginners
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
 
Mongo db basics
Mongo db basicsMongo db basics
Mongo db basics
 
Back to Basics Webinar 3: Schema Design Thinking in Documents
 Back to Basics Webinar 3: Schema Design Thinking in Documents Back to Basics Webinar 3: Schema Design Thinking in Documents
Back to Basics Webinar 3: Schema Design Thinking in Documents
 
MongoDB : The Definitive Guide
MongoDB : The Definitive GuideMongoDB : The Definitive Guide
MongoDB : The Definitive Guide
 
Python and MongoDB
Python and MongoDBPython and MongoDB
Python and MongoDB
 
Back to Basics: My First MongoDB Application
Back to Basics: My First MongoDB ApplicationBack to Basics: My First MongoDB Application
Back to Basics: My First MongoDB Application
 
Mongo DB Presentation
Mongo DB PresentationMongo DB Presentation
Mongo DB Presentation
 
Inside MongoDB: the Internals of an Open-Source Database
Inside MongoDB: the Internals of an Open-Source DatabaseInside MongoDB: the Internals of an Open-Source Database
Inside MongoDB: the Internals of an Open-Source Database
 
Mongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorials
Mongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorialsMongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorials
Mongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorials
 
Basics of MongoDB
Basics of MongoDB Basics of MongoDB
Basics of MongoDB
 
Intro To Mongo Db
Intro To Mongo DbIntro To Mongo Db
Intro To Mongo Db
 
Python and MongoDB
Python and MongoDB Python and MongoDB
Python and MongoDB
 
Building Your First MongoDB App
Building Your First MongoDB AppBuilding Your First MongoDB App
Building Your First MongoDB App
 

Similar a Mongo Presentation by Metatagg Solutions

171_74_216_Module_5-Non_relational_database_-mongodb.pptx
171_74_216_Module_5-Non_relational_database_-mongodb.pptx171_74_216_Module_5-Non_relational_database_-mongodb.pptx
171_74_216_Module_5-Non_relational_database_-mongodb.pptx
sukrithlal008
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
ADARSH BHATT
 
MongoDB (Advanced)
MongoDB (Advanced)MongoDB (Advanced)
MongoDB (Advanced)
TO THE NEW | Technology
 
MongoDb and NoSQL
MongoDb and NoSQLMongoDb and NoSQL
MongoDb and NoSQL
TO THE NEW | Technology
 

Similar a Mongo Presentation by Metatagg Solutions (20)

mongo.pptx
mongo.pptxmongo.pptx
mongo.pptx
 
fard car.pptx
fard car.pptxfard car.pptx
fard car.pptx
 
171_74_216_Module_5-Non_relational_database_-mongodb.pptx
171_74_216_Module_5-Non_relational_database_-mongodb.pptx171_74_216_Module_5-Non_relational_database_-mongodb.pptx
171_74_216_Module_5-Non_relational_database_-mongodb.pptx
 
MongoDB-presentation.pptx
MongoDB-presentation.pptxMongoDB-presentation.pptx
MongoDB-presentation.pptx
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
 
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
 
Php summary
Php summaryPhp summary
Php summary
 
MongoDB (Advanced)
MongoDB (Advanced)MongoDB (Advanced)
MongoDB (Advanced)
 
Php workshop L04 database
Php workshop L04 databasePhp workshop L04 database
Php workshop L04 database
 
phptut4
phptut4phptut4
phptut4
 
phptut4
phptut4phptut4
phptut4
 
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
 
Drupal II: The SQL
Drupal II: The SQLDrupal II: The SQL
Drupal II: The SQL
 
Mongo db queries
Mongo db queriesMongo db queries
Mongo db queries
 
Latinoware
LatinowareLatinoware
Latinoware
 
MongoDb and NoSQL
MongoDb and NoSQLMongoDb and NoSQL
MongoDb and NoSQL
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Edition
 
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
 
Php 102: Out with the Bad, In with the Good
Php 102: Out with the Bad, In with the GoodPhp 102: Out with the Bad, In with the Good
Php 102: Out with the Bad, In with the Good
 
Mongo db basics
Mongo db basicsMongo db basics
Mongo db basics
 

Ú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 slide
vu2urc
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Último (20)

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
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
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
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
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
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
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

Mongo Presentation by Metatagg Solutions

  • 1. - By Vijay Thakor
  • 2. What is MongoDB ? • MongoDB is an open source document database, and the leading NoSQL database. • MongoDB is a document orinted database that provides high performance, high availability, and easy scalability. • It is Maintained and supported by 10gen.
  • 3. What is NoSQL ? • NoSQL is a kind of database that, unlike most relational databases, does not provide a SQL interface to manipulate data. • NoSQL databases are divided into three categories: column-oriented, key-value pairs, and document-oriented databases.
  • 4. What is a document-oriented database? • For this type of databases, a document is a data structure that has variable number of properties. • Documents do not have a predefined schema like relational database tables. Documents can have multiple properties. Documents can also be grouped in collections.
  • 5. The mongoDB PHP extension • Maintained and supported by 10gen. • Can be installed with pecl: pecl install mongo • Add extension=mongo.so to php.ini • JSON Document: the data (row) • Collection: contains documents (table, view) • Index • Embedded Document (~join)
  • 6. Connecting to mongoDb No tables or collections have to do be explicitly created <?php $m = new Mongo(); $database = $m->demo; $collection = $database->testCollection; ?> Different connection strings: ● $m = new Mongo("mongodb://localhost"); ● $m = new Mongo("localhost:27017"); ● $m = new Mongo("mongodb://localhost:29000"); ● $m = new Mongo("mongodb://mongo.example.com"); ● $m = new Mongo("mongodb://mdb1.example.com,mdb2.example.com");
  • 7. Select a Database • If no database exists already, a new database is created. Currently there are two ways to do this: 1. $db = $connection->selectDB('dbname'); 2. $db = $connection->dbname; • Then it is necessary to select a collection to work with, like we would pick a table to work with when using relational databases. $collection = $db->selectCollection('people'); or simply $collection = $db->people;
  • 8. Documents • Stored as BSON (Binary JSON) • Can have embedded documents • Have a unique ID (the _id field) Simple document: { "_id" : ObjectId("4cb4ab6d7addf98506010001"), "id" : NumberLong(1), "desc" : "ONE" }
  • 9. Documents • Document with embedded documents: { "_id" : "derickr","name" : "Derick Rethans", "articles" : [ { "title" : "Profiling PHP Applications", "url" : "http://derickrethans.nl/talks/profiling-phptourlille11.pdf", }, { "title" : "Xdebug", "url" : "http://derickrethans.nl/talks/xdebug-phpbcn11.pdf", } ] }
  • 10. Inserting a document <?php $document = array( "_id" => "derickr", "name" => "Derick Rethans", "articles" => array( array( "title" => "Profiling PHP Applications", "url" => "http://derickrethans.nl/talks/profiling-phptourlille11.pdf", ), array( "title" => "Xdebug", "url" => "http://derickrethans.nl/talks/xdebug-phpbcn11.pdf", ) ) ); $m = new Mongo(); var_dump( $m->demo->articles->insert( $document ) ); ?>
  • 11. mongoDB supports many types • null • boolean • integer (both 32-bit and 64-bit, MongoInt32, • MongoInt64) • double • string (UTF-8) • array • associative array • MongoRegex • MongoId • MongoDate • MongoCode • MongoBinData
  • 12. Comparison with mysql • In Mysql, first we have to create database in phpmyadmin and then we have to select database by mysql_select_db(‘dbname’); • Where as in Mongodb no need to create database, database is created automatically when using it like $mongo = new Mongo(); $db = $mongo->selectDB(“test”); With Authentication: $mongo = new Mongo(“mongodb://{$username}:{$password}@{$host}”); $db = $mongo->selectDB(“test”);
  • 13. Comparison with mysql • In mysql after creating and selecting database we can create table as CREATE TABLE authors (id INT, name VARCHAR(20), email VARCHAR(20)); • Where as in Mongodb we can create collection(table) like $mongo = new Mongo(); $db = $mongo->selectDB(“test”); $db->createCollection(“people”,false);
  • 14. Comparison with mysql • In mysql, after selecting database we can insert data into table with the help of query like $query = ‘insert into table_name (‘fields name’) values(‘values’);’ mysql_query($query); • Where as in mongoDb we insert data like, $people = $db->people; $insert = array(“user” => “demo@9lessons.info”, “password” => md5(“demo_password”)); $db->insert($insert); Where people is the collection name.
  • 15. Comparison with mysql • In mysql, after selecting database we can Update data into table with the help of query like $query = ‘UPDATE table_name SET fields name = ‘value’; mysql_query($query); • Where as in mongoDb we Update data like, $update = array(“$set” => array(“user” => “demo@9lessons.info”)); $where = array(“password” => “password”); $people->update($where,$update); Mongo Shell: db.people.update({password:”password”},{$set : {user:”demo@demo.com”}});
  • 16. Comparison with mysql • Finally we can use select query to select data from the table of database like below query in mysql, $query = ‘select * from table where field_name = ‘value’’; • Where as in mongoDb we use following query to select data from collections An empty query document ({}) selects all documents in the collection: db.inventory.find( {} )
  • 17. Comparison with mysql • A single-clause query selects all documents in a collection where a field has a certain value. These are simple, “equality” queries. 1. Fetch people by e-mail address: $filter = array('email' => 'crodas@php.net'); $cursor = $collection->find($filter); foreach ($cursor as $user) { var_dump($user); }
  • 18. Comparison with mysql 2. Fetch people who has more than ten sessions. $filter = array('sessions' => array('$gt' => 10)); $cursor = $collection->find($filter); Fetch people that do not have the sessions property set $filter = array( 'sessions' => array('$exists' => false) ); $cursor = $collection->find($filter);
  • 19. Comparison with mysql 3. Fetch people that have an address in Paraguay and have more than 15 sessions $filter = array( 'address.country' => 'PY', 'sessions' => array('$gt' => 10) ); $cursor = $collection->find($filter); One important detail worth mentioning is that queries are not executed until the result is actually requested. In the first example the query is executed when the foreach loop starts.
  • 20. Comparison with mysql • Sorting Records What if we want to sort records, say by first name or nationality? Similar to SQL, Mongo provides the sort command. The command, like the find command takes a list of options to determine the sort order. Unlike SQL, however we specify ascending and descending differently. We do that as follows: 1. Ascending: -1 2. Descending: 1 • Let’s have a look at an example:
  • 21. Comparison with mysql db.collection.find({gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'}]}).sort({nationality: -1}); This example retrieves all male, English or American, actors and sorts them in descending order of nationality. • Limiting Records What if we had a pretty big data set (lucky us, we don’t) and we wanted to limit the results to just 2? Mongo provides the limit command, similar to MySQL and allows us to do just that. Let’s update our previous query and return just 2 records. Have a look at the following command: • db.collection.find({gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'}]}).limit(2);
  • 22. Login Example in mongoDb • Finally it’s time to do small example using mongoDb as database, let’s create login process with mongoDb. • First we have to create login form like, <form action="index.php" method="POST"> Email: <input type="text" id="usr_email" name="usr_email" /> Password: <input type="password" id="usr_password" name="usr_password" /> <input name="submitForm" id="submitForm" type="submit" value="Login"/> </form>
  • 23. Login Example in mongoDb • And the php Process page like, <?php $succss = ""; if(isset($_POST) and $_POST['submitForm'] == "Login" ) { $usr_email = mysql_escape_string($_POST['usr_email']); $usr_password = mysql_escape_string($_POST['usr_password']); $error = array(); // Email Validation if(empty($usr_email) or !filter_var($usr_email,FILTER_SANITIZE_EMAIL)) { $error[] = "Empty or invalid email address"; } if(empty($usr_password)){ $error[] = "Enter your password"; }
  • 24. Login Example in mongoDb • if(count($error) == 0){ $con = new Mongo(); if($con){ // Select Database $db = $con->test; // Select Collection $people = $db->people; $qry = array("user" => $usr_email,"password" => md5($usr_password)); $result = $people->findOne($qry); if($result){ $success = "You are successully loggedIn"; // Rest of code up to you.... } } else { die("Mongo DB not installed"); } }} ?>
  • 25. Blog system with mongoDb lets say you want to build a blog system with users, posts and comments. You would implement it defining with a table schema like this when using a relational database.
  • 26. Blog system with mongoDb • The equivalent document definition that represents the same structures in MongoDB would be defined like this: • $users = array( 'username' => 'crodas', 'name' => 'Cesar Rodas', ); $posts = array( 'uri' => '/foo-bar-post', 'author_id' => $users->_id, 'title' => 'Foo bar post', 'summary' => 'This is a summary text', 'body' => 'This is the body', 'comments' => array( array( 'name' => 'user', 'email' => 'foo@bar.com', 'content' => 'nice post' ) ) );
  • 27. Blog system with mongoDb • As you may notice, we only need one document to represent both the posts and comments. That is because comments are sub-documents of post documents. • This makes the implementation much simpler. It also saves time to query the database when you want to access either a post and its comments. • To make it even more abbreviated, the details of the users making comments could be merged with the comment definitions, so you can retrieve either the posts, comments and users with a single query. • $posts = array( 'uri' => '/foo-bar-post', 'author_id' => $users->_id, 'author_name' => 'Cesar Rodas', 'author_username' => 'crodas', 'title' => 'Foo bar post', 'summary' => 'This is a summary text',
  • 28. Blog system with mongoDb 'body' => 'This is the body', 'comments' => array( array( 'name' => 'user', 'email' => 'foo@bar.com', 'comment' => 'nice post' ), ) ); • This means that some duplicated information may exist, but keep in mind that disk space is much cheaper than CPU and RAM, and even more important that the time and patience of your site visitors.
  • 29. Blog system with mongoDb • If you are concerned with synchronization of duplicated information, you can solve that problem by executing this update query when the author updates his profile: • $filter = array( 'author_id' => $author['_id'], ); $data = array( '$set' => array( 'author_name' => 'Cesar D. Rodas', 'author_username' => 'cesar', ) ); $collection->update($filter, $data, array( 'multiple' => true) );
  • 30. Blog system with mongoDb • Given these optimizations of our data model, lets rewrite some SQL as equivalent queries to MongoDB. SELECT * FROM posts INNER JOIN users ON users.id = posts.user_id WHERE URL = :url; SELECT * FROM comments WHERE post_id = $post_id; • First, add this index just once: $collection->ensureIndex( array('uri' => 1), array('unique' => 1, 'background') ); $collection->find(array('uri' => '<uri>'));
  • 31. Blog system with mongoDb • INSERT INTO comments(post_id, name, email, contents) VALUES(:post_id, :name, :email, :comment); • $comment = array( 'name' => $_POST['name'], 'email' => $_POST['email'], 'comment' => $_POST['comment'], ); $filter = array( 'uri' => $_POST['uri'], ); $collection->update($filter, array( '$push' => array('comments' => $comment)) );
  • 32. Blog system with mongoDb • SELECT * FROM posts WHERE id IN ( SELECT DISTINCT post_id FROM comments WHERE email = :email ); First, add this index just once: $collection->ensureIndex( array('comments.email' => 1), array('background' => 1) ); $collection->find( array('comments.email' => $email) );