Mongo Presentation by Metatagg Solutions
-
Upload
metatagg-solutions -
Category
Technology
-
view
1.360 -
download
1
description
Transcript of Mongo Presentation by Metatagg Solutions
- 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” => “[email protected]”, “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” => “[email protected]”));
$where = array(“password” => “password”); $people->update($where,$update);
Mongo Shell: db.people.update({password:”password”},{$set : {user:”[email protected]”}});
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' => '[email protected]'); $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' => '[email protected]', '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' => '[email protected]', '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