MongoDB and PHP

1) Download and Install MongoDB

In order to download and install MongoDB, first download a package from

http://www.mongodb.org/downloads

If you are running Windows XP, use 2.0.X.  Otherwise use the latest stable production build.

Here is the main link for mongo installation.

http://docs.mongodb.org/manual/tutorial/install-mongodb-on-windows/

2) Download the correct MongoDB PHP driver

The repository for MongoDB PHP drivers is located at:

https://github.com/mongodb/mongo-php-driver/downloads

I grabbed the latest release, which at the time of this writing is php_mongo-1.3.1.zip.

This php_mongo-1.3.1.zip package contains several different PHP versions of the DLL.  To see which version of PHP you are running, go to the XAMPP Control Panel and click Apache -> Admin.  This will bring up a splash window.  Click on phpinfo() on the left and you can see what type of installation you have.  In my case this is PHP 5.4.4, running in 32-bit mode, with VC9 for the compiler, and running in thread-safe mode.

Since I’m running a 32-bit version of windows this narrows it down even more.  My options are either not thread-safe (nts) or thread-safe.  I’m going to pick thread-safe because I think this is the default value for XAMPP.  So I copy the file php_mongo-1.3.1-5.4-vc9.dll to the extensions directory.  In my case this is c:xamppphpext.  Then I rename the dll to php_mongo.dll

3) Point to driver in php.ini file

Add the line below to the php.ini file.  Then restart the webserver.

extension=php_mongo.dll

If all went well you should have a mongo section in your phpinfo() section.

4) Try an example file

Create a PHP file that creates an instance of Mongo in order to see if it’s done right.

<?php

// create a mongo instance
$m = new Mongo();

// select a database
$db = $m->play;

// select a collection (this is mongo version of a table in a releational database
$collection = $db->app;

$obj = array( “title” => “RunSafe”, “reviews” => 100);
$collection->insert($obj);

//get everything in the collection
$everything = $collection->find();

foreach ($everything as $thing) {
echo $thing[“title”] . “n”;
}
?>

Thinks that go wrong

1) I tried to install Mongo 2.2 on my Windows XP box and got a DLL error.  Windows XP only works up to 2.0

2) Must make sure to restart the webserver after changing the php.ini file

3) Must make sure to use the correct DLL file based on what’s found in phpinfo.

4) Error: couldn’t connect to server 127.0.0.1 shell/mongo.js:84

This happens because I didn’t shut down MongoDB properly.  It left a “mongod.lock” file.  To fix this I

a) deleted the mongod.lock file

b) “c:Program Filesmongodbbinmongod.exe” –dbpath “c:Documents and SettingsChrisdatadb” –repair

This should get it all cleaned up.  Now to launch it again do

“c:Program Filesmongodbbinmongod.exe” –dbpath “c:Documents and SettingsChrisdatadb”

Speak Your Mind

*

DSCF0006