MongoDb with PHP configuration and tutorial for beginner

php-mongo

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

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();
// iterate through the results
echo "";foreach($resultas$resultSet){echo"";}echo"
TitleDescription
".$resultSet["title"] . "".$resultSet["description"]."
"

“;
foreach ($result as $resultSet) {
echo “

“;
}
echo “

Title Description
“.$resultSet[“title”] . “ “.$resultSet[“description”].”

Complete source file:

 

// connect
$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 "";foreach($resultas$resultSet){echo"";}echo"
TitleDescription
".$resultSet["title"] . "".$resultSet["description"]."
"
?>

“;
foreach ($result as $resultSet) {
echo “

“;
}
echo “

Title Description
“.$resultSet[“title”] . “ “.$resultSet[“description”].”


?>

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

Leave a Reply

Your email address will not be published. Required fields are marked *

Top