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

Contenu connexe

Tendances

Building Apps with MongoDB
Building Apps with MongoDBBuilding Apps with MongoDB
Building Apps with MongoDBNate Abele
 
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 NoSQLMongoDB
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDBNosh Petigara
 
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 DocumentsMongoDB
 
MongoDB for Beginners
MongoDB for BeginnersMongoDB for Beginners
MongoDB for BeginnersEnoch Joshua
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDBantoinegirbal
 
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 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 DocumentsMongoDB
 
MongoDB : The Definitive Guide
MongoDB : The Definitive GuideMongoDB : The Definitive Guide
MongoDB : The Definitive GuideWildan Maulana
 
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 ApplicationMongoDB
 
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 DatabaseMike Dirolf
 
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 tutorialsSpringPeople
 
Basics of MongoDB
Basics of MongoDB Basics of MongoDB
Basics of MongoDB Habilelabs
 
Intro To Mongo Db
Intro To Mongo DbIntro To Mongo Db
Intro To Mongo Dbchriskite
 
Building Your First MongoDB App
Building Your First MongoDB AppBuilding Your First MongoDB App
Building Your First MongoDB AppHenrik Ingo
 

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

Similaire à 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.pptxsukrithlal008
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2ADARSH BHATT
 
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
 
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
 
Drupal II: The SQL
Drupal II: The SQLDrupal II: The SQL
Drupal II: The SQLddiers
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Editionddiers
 
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 GoodJeremy Kendall
 

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

Dernier

AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
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.pdfsudhanshuwaghmare1
 
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...Miguel Araújo
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 

Dernier (20)

AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
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
 
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...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 

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) );