How to configure mongodb with php using ubuntu

save image Export MySQL Database configure mongodb send email from localhost

How to configure mongodb with php using ubuntu. this is very useful detail for Who don’t know for configue monogdb.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.

Also Read: How to integrte SMS API in PHP

Here is step for configure mongodb with php using ubuntu

Fist you need to install MongoDb in your system

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();
// iterate through the results
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
// 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 "<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.

Leave a Reply