This is Part 1 of a series of short posts on how to use MongoDB with PHP.
Installing MongoDB support for PHP is really easy! Here’s a short howto guide for installing MongoDB for PHP and preforming a simple query.
Install MongoDB for PHP Support

Unix/Linux
Via your command line run pecl:
$ sudo pecl install mongo
If you get an error saying the system can’t find `phpize` then you may need to install the PHP dev package …
$ sudo aptitude install php5-dev
You will then need to edit your php.ini file add add the mongo.so extension:
extension=mongo.so
Just restart your webserver and you are done.
Windows
Installing on windows is just as easy. Firsst, you will need to get the binaries from here and then add the proper .dll to your php.ini:
extension=php_mongo.dll
Create Test Collection
Now we will create a test collection in the default ‘test’ database … bring up your mongoDB shell by running:
$ mongo
Then, insert a document like the following:
MongoDB shell version: 1.6.1
connecting to: test
> doc = { "hello" : "world", "php" : "is alive!" };
> db.phptest.save(doc);
Now let’s just query it to make sure everything is good …
> db.phptest.findOne();
{
"_id" : ObjectId("4c75add543dd9c1e48177f49"),
"hello" : "world",
"php" : "is alive!"
}
Great!
Connect to MongoDB

Next, we’ll connect to our MongoDB server.
Create a PHP file and add the following:
<?php $connection = new Mongo(); $db = $connection->test; $collection = $db->phptest; ?>
This will connect us to the ‘test’ Database and then to our ‘phptest’ Collection.
Query and Display MongoDB Data
Now, add these lines below your connection:
<?php $connection = new Mongo(); $db = $connection->test; $collection = $db->phptest; $obj = $collection->findOne(); echo "<h1>Hello " . $obj["hello"] . "!</h1>"; echo "<h2>Show result as an array:</h2>"; echo "<pre>"; print_r($obj); echo "</pre>"; echo "<h2>Show result as JSON:</h2>"; echo "<pre>"; echo json_encode($obj); echo "</pre>"; ?>
Hello World
Save your PHP page and bring it up in your browser.
You should get back:
- Hello World
- An array showing your document.
- As well as your document in JSON.
What Just Happened?
We ran the findOne(); command against our Collection …
$obj = $collection->findOne();
We got back $obj which contained the Document we inserted earlier. Then we got the value of the “hello” attribute (which is “world”) of the object $obj …
echo "<h1>Hello " . $obj["hello"] . "!</h1>";
Then we pass the same object to print_r() … to see it as an array and then to json_encode() … to see it as JSON.
What’s Next …
In the next part of this series we’ll handle more complex queries as well as inserts and updates.



Pingback: MongoDB and 64-bit Integers in PHP | LearnMongo.com
Pingback: Introduction to MongoDB » By Justin Jenkins » Featured, NoSQL