Mammatus Blog‎ > ‎

Installing MongoDB Database to work with PHP and Apache (tutorial)

posted Sep 30, 2012, 2:24 PM by Rick Hightower   [ updated Sep 30, 2012, 3:15 PM ]

Installing and setting up MongoDB to work with PHP

See installing MongoDB to install MongoDB.

Node.js , Ruby, and Python in that order are the trend setter crowd in our industry circa 2012. Java is the corporate crowd, and PHP is the workhorse of the Internet. The "get it done" crowd. You can't have a decent NoSQL solution without having good PHP support. Installing MongoDB to work with PHP is simple.

To install MongoDB support with PHP use pecl as follows:

$ sudo pecl install mongo

Add the mongo.so module to php.ini.

extension=mongo.so

Then assuming you are running it on apache, restart as follows:

$ apachectl stop
$ apachectl start

Figure 1 shows our roughly equivalent code listing in PHP.

Figure 1 PHP code listing

PHP MongoDB

The output for figure 1 is as follows:

Output:
array ( '_id' => MongoId::__set_state(array( '$id' => '4f964d3000b5874e7a163895', )), 'name' => 'Rick Hightower', 
'gender' => 'm', 'phone' => '520-555-1212', 'age' => 42, )

array ( '_id' => MongoId::__set_state(array( '$id' => '4f984cae72329d0ecd8716c8', )), 'name' => 'Diana Hightower', 'gender' => ‘f', 
'phone' => '520-555-1212', 'age' => 30, )

array ( '_id' => MongoId::__set_state(array( '$id' => '4f9e170580cbd54f27000000', )), 'gender' => 'm', 'age' => 8, 'name' => 'Lucas Hightower', 
'phone' => '520-555-1212', )

The other half of the equation is in figure 2.

Figure 2 PHP code listing

PHP, MongoDB

The output for figure 2 is as follows:

Output
Rick? 
array ( '_id' => MongoId..., 'name' => 'Rick Hightower', 'gender' => 'm', 
'phone' => '520-555-1212', 'age' => 42, )
Diana? 
array ( '_id' => MongoId::..., 'name' => 'Diana Hightower', 'gender' => ‘f', 
'phone' => '520-555-1212', 'age' => 30, )
Diana by id? 
array ( '_id' => MongoId::..., 'name' => 'Diana Hightower', 'gender' => 'f', 
'phone' => '520-555-1212', 'age' => 30, )

Here is the complete PHP listing.

PHP complete listing

<!--?php

$m = new Mongo();
$db = $m->selectDB("tutorial");
$employees = $db->selectCollection("employees");
$cursor = $employees->find();

foreach ($cursor as $employee) {
  echo var_export ($employee, true) . "< br />";
}

$cursor=$employees->find( array( "name" => "Rick Hightower"));
echo "Rick? < br /> " . var_export($cursor->getNext(), true);

$cursor=$employees->find(array("age" => array('$lt' => 35)));
echo "Diana? < br /> " . var_export($cursor->getNext(), true);

$cursor=$employees->find(array("_id" => new MongoId("4f984cce72320612f8f432bb")));
echo "Diana by id? < br /> " . var_export($cursor->getNext(), true);
?>

If you like Object mapping to documents you should try the poorly named MongoLoid for PHP.

If you would like to learn more about MongoDB consider the following resources:

    Mongo DB is wrong. It is MongoDB. Always put the DB next to Mongo. 
    Comments