MongoDb with PHP configuration and tutorial for beginner

In this tutorial i am going to show you some basics of working with mongoDb NoSql database with php, We all know NoSql databases are getting popularity day by day because of it’s Key Pair pattern in Json like storage database, If you need fast performance result from your database then you must go with NoSql database like MongoDb.

Here you’ll learn how to install and configure MongoDb-PHP driver in your ubuntu machine and How to make connection and insert, fetch data from MongoDb database.




Fist you need to install MongoDb in your system see this tutorial: How to Install and Configure MongoDB on Ubuntu 14.04

After that install PHP-MongoDb driver and restart apache by running below command in terminal

sudo apt-get install php5-mongo
sudo service apache2 restart

Now create php file and make connection with mongoDb

$MClient = new MongoClient();

Above command will connect your localhost MongoDb

If your mongoDb sever is some where else then

$MClient = new MongoClient( "mongodb://example.com:27017" );

Here i am going to create a blog table in MongoDB and will store some article in articles collection

Select / Create database

$db = $MClient->blog;

Select a collection

$collection = $db->articles

Insert some sample articles

$article = array( "title" => "Title-1", "description" => "Description-1" );
$collection->insert($article);
 
$article = array( "title" => "Title-2", "description" => "Description-2", "status" => true );
$collection->insert($article);




Fetch stored articles from MongoDb.

$result = $collection->find();

echo "<table border=1><tr><th>Title</th><th>Description</th></tr>";
foreach ($result as $resultSet) {
    echo "<tr><td>".$resultSet["title"] . "</td><td>".$resultSet["description"]." </td></tr>";
}
echo "</table>"

Complete source file:

 
<?php

$MClient = new MongoClient();
 
$db = $MClient->blog;
 
$collection = $db->articles;
 
$article = array( "title" => "Title-1", "description" => "Description-1" );
$collection->insert($article);
 
$article = array( "title" => "Title-2", "description" => "Description-2", "status" => true );
$collection->insert($article);
 
$result = $collection->find();
 
echo "<table border=1><tr><th>Title</th><th>Description</th></tr>";
foreach ($result as $resultSet) {
    echo "<tr><td>".$resultSet["title"] . "</td><td>".$resultSet["description"]." </td></tr>";
}
echo "</table>"
?>

Execute your file on web and see output.
php-mongo

If you like this post please don’t forget to subscribe my public notebook for more useful stuff