Amazon AMI install MongoDB Driver

Did an installation of MongoDB driver for PHP on my Amazon EC2 AMI just now. And thought of noting the steps down.


Prerequisites 

Make sure the following packages are installed.
$ sudo yum install gcc
$ sudo yum install make

$ sudo yum install httpd mod_ssl
$ sudo yum install php
$ sudo yum install php-devel php-pear
$ sudo yum install pcre-devel

Install MongoDB driver for Amazon Linux

Installing Mongo driver.
$ sudo pecl install mongo


Enable the driver
$ sudo vi /etc/php.d/mongo.ini
$ extension=mongo.so
$ sudo  /sbin/service httpd restart


Testing

The simplest way to check whether the installation is successful is via phpinfo().
<?php
  phpinfo();
?>
And you should see the following section:



Or test the connection using the code snippet below :)
<?php
 // connect
 $m = new Mongo("mongodb://mongodb-user:mongodb-password@ds031087.mongolab.com:31087/sample-test-mongodb");
 
 // select a database
 $db = $m->{"sample-test-mongodb"};
 
 // select a collection (analogous to a relational database's table)
 $collection = $db->cartoons;
 
 // add a record
 $obj = array( "title" => "Calvin and Hobbes", "author" => "Bill Watterson" );
 // $collection->insert($obj);
 
 // add another record, with a different "shape"
 $obj = array( "title" => "XKCD", "online" => true );
 // $collection->insert($obj);
 
 // find everything in the collection
 $cursor = $collection->find();
 
 // iterate through the results
 foreach ($cursor as $obj) {
     echo $obj["title"] . "\n";
 }
?>
And you should see following output in browser:



Its quite simple, but hope this help beginners out there :)


Comments

Post a Comment

Popular posts from this blog

[Azure Websites PHP] Cross Domain request results in blank response page after Preflight HTTP OPTIONS

[Magento] Create Contact Form with Dynamic Recipient