MongoDB+PHP: Install and Connect

in PHP

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.

9 Comments
  • Pingback: MongoDB and 64-bit Integers in PHP | LearnMongo.com

  • Pingback: Introduction to MongoDB » By Justin Jenkins » Featured, NoSQL

  • Hungtaoquang

    Hi! After using json_encode, I use json_decode and then, I can not get my _id
    {
    “_id” : ObjectId(“4c75add543dd9c1e48177f49″),
    “hello” : “world”,
    “php” : “is alive!”
    }

    Here is my code:
    $collection = …
    $obj = $collection->findOne();
    echo $obj["_id"] //output: 4c75add543dd9c1e48177f49
    $strVar = json_encode($obj);

    $obj2 = json_decode($strVar, true);
    echo $obj2["_id"] //output: nothing….

    Thanks for you help!

  • http://www.facebook.com/briankulp Brian Kulp

    Such a helpful post. Hoping for part 2 :)

  • Anonymous

    Yeah, this was exactly what I was looking for to help get started. Thanks for posting!!

  • http://twitter.com/bbboooeee boe var

    Same with kevinnayar’s comment.

  • http://twitter.com/You43Ru you43.ru

    создание сайтов http://mediakirov.ru (в Кирове)

  • http://chars19.blogspot.com/ Ardi

    i am using php version 5.4 and always error with mongodb driver. the only solution is downgrade to 5.3.

    and iam still happy with mongo. :)

  • Rohit

    Hi ,

    I am using Ubuntu 12.04. I have installed mongodb in my system and able to do crud operation using terminal but when I try to do the same using php it shows blank page. It fails. I have added the extension=mongo.so already.

    Can you please let me know where I am doing wrong.