Manas Tungare

HOWTO Install MongoDB for PHP on Mac OS X

MongoDB is a document-oriented database (among other things), and it’s especially convenient that the native document format is JSON. For various ongoing pet projects, I figured I’d give it a try to avoid the overhead of creating/maintaining schemas and having to flatten down my JSON objects to fit a relational model.

These instructions work for 10.7 Lion, 10.6 Snow Leopard and 10.5 Leopard. The steps outlined here ensure that your MongoDB installation integrates well with the rest of the system (Apache, PHP & launchd), is started automatically when the machine starts up, and makes it easy to upgrade later.

I read a lot of conflicting instructions on the Web about how to install MongoDB, and they’re either incomplete (most of them skip the part about making MongoDB run automatically at startup), and none of them satisfied the following requirements I had:

  • I should not need to install any software that’s already present on a stock Mac OS X installation (Lion, Snow Leopard or Leopard, at the very least.)
  • It should be relatively easy to upgrade the base version of MongoDB, so installing it via a package manager would be preferable to installing it from source.
  • The MongoDB server should be started up automatically through system-standard tools such as launchd — not manually every time I need to test something.

This tutorial assumes a virgin Mac OS X installation. If you already have a component installed, simply skip that step.

  1. Install XCode from the Mac App Store. It’s needed for MacPorts.

  2. Install MacPorts from macports.org. MacPorts is a package manager for Mac OS X that makes it easy to install and configure a lot of open-source software.

    Although MongoDB binaries are available from the MongoDB web site, I strongly recommend using the MacPorts MongoDB port. MacPorts ensures dependencies are installed correctly, and provides an easy way to upgrade all outdated packages at once.

Install and configure MongoDB

  1. Install MongoDB. Open a Terminal, ensure you’re using an account with Administrator privileges, and type:

          sudo port install mongodb

    That’s it, MongoDB is now installed. But there’s lots more to do to get it working.

  2. Create directories required by MongoDB.

          # The data directory.
          sudo mkdir -p /var/lib/mongodb/
          
          # The logs directory.
          sudo mkdir -p /var/log/mongodb/
  3. Create a config file. Put this in a new file at /etc/mongodb.conf:
          # This is an example config file for MongoDB.
          # Place it at /etc/mongodb.conf
          # Based on a sample provided at 
          # http://www.mongodb.org/display/DOCS/File+Based+Configuration
          dbpath = /var/lib/mongodb
          bind_ip = 127.0.0.1
          noauth = true
  4. Configure a launchd LaunchDaemon. Put this in a new file at /Library/LaunchDaemons/org.mongo.mongod.plist.

          <?xml version="1.0" encoding="UTF-8"?>
          <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
            "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
          <plist version="1.0">
          <dict>
            <key>Label</key>
            <string>org.mongodb.mongod</string>
            <key>ProgramArguments</key>
            <array>
              <string>/opt/local/bin/mongod</string>
              <string>run</string>
              <string>--config</string>
              <string>/etc/mongodb.conf</string>
            </array>
            <key>RunAtLoad</key>
            <true/>
            <key>KeepAlive</key>
            <true/>
            <key>WorkingDirectory</key>
            <string>/var/log/mongodb/</string>
            <key>StandardErrorPath</key>
            <string>/var/log/mongodb/output.log</string>
            <key>StandardOutPath</key>
            <string>/var/log/mongodb/output.log</string>
          </dict>
          </plist>
  5. Start MongoDB via launchd. Type in a Terminal window:

          sudo launchctl load /Library/LaunchDaemons/org.mongo.mongod.plist

You can stop reading now if all you need is MongoDB and don’t plan to use PHP with it. The MongoDB server will be automatically launched at startup.

Enable Apache and PHP5

  1. Start Apache. In System Preferences, go to Sharing, and then check the box next to “Web Sharing”.

  2. Enable PHP5 support in Apache. Open the Apache config file, /etc/apache2/httpd.conf, and locate the following line.

          # LoadModule php5_module

    Uncomment that line, so it reads:

          LoadModule php5_module
        
  3. Restart Apache. Type in a Terminal window:

          sudo apachectl graceful
        
  4. Test if PHP is working correctly. Create a new PHP file at /Library/WebServer/Documents/phpinfo.php and put in it:

          <?php
            phpinfo();
          ?>

    Browse to http://localhost/phpinfo.php, and you should see a long page showing your PHP configuration.

    Apache and PHP5 are now configured.

Install and Configure the PHP5 MongoDB driver.

  1. Install PEAR. PEAR is the PHP Extension and Application Repository, from which we’ll install the PHP5 MongoDB driver.

          $ cd /tmp
          $ wget http://pear.php.net/go-pear.phar
          $ sudo php -d detect_unicode=0 go-pear.phar

    You’ll be prompted with a default file layout. I changed this to install it in /usr/local/pear instead of under /Users/Admin.

          Below is a suggested file layout for your new PEAR installation.  To
          change individual locations, type the number in front of the
          directory.  Type 'all' to change all of them or simply press Enter to
          accept these locations.
    
           1. Installation base ($prefix)                   : /Users/Admin/pear
           2. Temporary directory for processing            : /tmp/pear/install
           3. Temporary directory for downloads             : /tmp/pear/install
           4. Binaries directory                            : /Users/Admin/pear/bin
           5. PHP code directory ($php_dir)                 : /Users/Admin/pear/share/pear
           6. Documentation directory                       : /Users/Admin/pear/docs
           7. Data directory                                : /Users/Admin/pear/data
           8. User-modifiable configuration files directory : /Users/Admin/pear/cfg
           9. Public Web Files directory                    : /Users/Admin/pear/www
          10. Tests directory                               : /Users/Admin/pear/tests
          11. Name of configuration file                    : /Users/Admin/.pearrc
    
          1-11, 'all' or Enter to continue:

    At this prompt, type 1

          (Use $prefix as a shortcut for '/Users/Admin/pear', etc.)
          Installation base ($prefix) [/Users/Admin/pear] :

    At this prompt, type /usr/local/pear

          Below is a suggested file layout for your new PEAR installation.  To
          change individual locations, type the number in front of the
          directory.  Type 'all' to change all of them or simply press Enter to
          accept these locations.
    
           1. Installation base ($prefix)                   : /usr/local/pear
           2. Temporary directory for processing            : /tmp/pear/install
           3. Temporary directory for downloads             : /tmp/pear/install
           4. Binaries directory                            : /usr/local/pear/bin
           5. PHP code directory ($php_dir)                 : /usr/local/pear/share/pear
           6. Documentation directory                       : /usr/local/pear/docs
           7. Data directory                                : /usr/local/pear/data
           8. User-modifiable configuration files directory : /usr/local/pear/cfg
           9. Public Web Files directory                    : /usr/local/pear/www
          10. Tests directory                               : /usr/local/pear/tests
          11. Name of configuration file                    : /Users/Admin/.pearrc
    
          1-11, 'all' or Enter to continue:

    At this prompt, type 11

          (Use $prefix as a shortcut for '/usr/local/pear', etc.)
          Name of configuration file [/Users/Admin/.pearrc] :

    At this prompt, type /etc/pearrc

          Below is a suggested file layout for your new PEAR installation.  To
          change individual locations, type the number in front of the
          directory.  Type 'all' to change all of them or simply press Enter to
          accept these locations.
    
           1. Installation base ($prefix)                   : /usr/local/pear
           2. Temporary directory for processing            : /tmp/pear/install
           3. Temporary directory for downloads             : /tmp/pear/install
           4. Binaries directory                            : /usr/local/pear/bin
           5. PHP code directory ($php_dir)                 : /usr/local/pear/share/pear
           6. Documentation directory                       : /usr/local/pear/docs
           7. Data directory                                : /usr/local/pear/data
           8. User-modifiable configuration files directory : /usr/local/pear/cfg
           9. Public Web Files directory                    : /usr/local/pear/www
          10. Tests directory                               : /usr/local/pear/tests
          11. Name of configuration file                    : /etc/pearrc
    
          1-11, 'all' or Enter to continue:

    At this prompt, type <Enter>

          Would you like to alter php.ini </private/etc/php.ini>? [Y/n] :

    At this prompt, type Y.

  2. Install the PHP MongoDB driver.

          sudo /usr/local/pear/bin/pecl install mongo
  3. Configure the system PHP to load that extension. Add this line to your php.ini. (If you don’t know where your php.ini file is located, go back to the phpinfo page that you created earlier, and you’ll find it on that page.)

          extension=mongo.so
  4. Restart Apache. To enable PHP5 with MongoDB support, restart Apache.

          sudo apachectl graceful

Test your installation.

  1. Create a simple test script. Create a PHP file at /Library/WebServer/Documents/mongodb.php

          <?php
            $mongoDB = new Mongo();
            $database = $mongoDB->selectDB("example");
            $collection = $database->createCollection('TestCollection');
            $collection->insert(array('test' => 'Test OK'));
    
            $retrieved = $collection->find();
            foreach ($retrieved as $obj) {
              echo($obj['test']);
            }
          ?>
  2. Test the installation. Browse to http://localhost/mongodb.php. If you see the following output, then congratulations, MongoDB is properly installed and configured to work with PHP on your Mac. Happy developing!

          Test OK

If this worked well for you, or if it doesn’t work for your specific configuration, please let me know via the comments, and perhaps we can troubleshoot.

Comments

  1. [...] HOWTO Install MongoDB for PHP on Mac OS X – Manas Tungare Bookmark to: This entry was posted in Uncategorized and tagged integrates-well, machine, [...]

    HOWTO Install MongoDB for PHP on Mac OS X – Manas Tungare | Internet blog — August 15, 2011

  2. Been playing with MongoDB on Mac myself — though not using auto-update via MacPorts. Nice reference – look forward to hearing how usage turns out.

    Nitya Narasimhan — August 15, 2011

  3. I got into some hell with MacPorts a while ago, and switched to Homebrew. Never looked back.

    Anish Nair — August 15, 2011

  4. What was the trouble with MacPorts? I haven't had trouble with it so far; it's been pretty good with managing multiple versions as well.

    Manas Tungare — August 15, 2011

  5. MacPorts got hosed after I upgraded to Snow Leopard, I didn't expect that. I don't remember the details, but I think the main issue is that it tries to maintain its own dependency graph. Homebrew is simpler, it reuses stuff you have on your system already. I've used it on multiple computers now, and upgraded to Lion etc., no issues. I guess if you're looking to replace stuff already on your mac (python, ruby, apache), MacPorts is the way to go. On the other hand, if you're using relatively standalone tools like MongoDB, Homebrew might be simpler.

    Anish Nair — August 15, 2011

  6. +Rahul Saxena I don't know much about HTML 5 interfaces, but I'm fairly certain you won't find anything that does something this specific out of the box. First off, do you need local storage or a distributed data source?

    Anish Nair — August 16, 2011

  7. Local (Client Side) storage only. I am open to any language binding on the client-side

    Rahul Saxena — August 16, 2011

  8. Rahul, IndexedDB seems like what you're looking for. It doesn't use the File API, but the data is all stored by the browser in the user's profile.

    Manas Tungare — August 16, 2011

  9. Yeah, MongoDB is not meant for client-side stuff.

    I'd never heard of IndexedDB, looks cool, but is there a concrete implementation, looks like a specification? SQLite with its wide language support would have been my first choice for client-side storage. And LevelDB is probably worth investigating as well.

    Anish Nair — August 16, 2011

  10. Thank you for your instructions.

    They were most helpful

    Scott — September 8, 2011

  11. Thanks a lot for these installation instructions. I had MongoDB already installed several months ago on Snow Leopard and wanted everything back on a fresh installation of Mac OS X Lion. As I had Apache and PHP already running, because it’s shipped with the OS as we know, all I really needed was the PHP extension (mongo.so). I don’t really understand why you can’t just download it somewhere, which I did successfully several months ago – after a lot of searching though.

    If some readers of this post feel it’s still too complicated, here’s my shortcut assuming they’ve got the Mac OS’s default Apache and PHP already running and just want to add MongoDB support as fast and easy as possible:

    (1) Skip steps 1 to 3. Step No 3 takes ages to build everything and to date from MacPorts all you get is MongoDB 1.8.3. Download MongoDB 2.0.0 (or whatever the latest version is) binaries from http://www.mongodb.org/downloads. Unzip wherever you want and you’re ready to run MongoDB.

    (2) Download my PHP extension I’ve built to skip steps 11 and 12 from http://bit.ly/mongoso, unzip and copy the file to the right place (sudo cp mongo.so /usr/lib/php/extensions/no-debug-non-zts-20090626/) and continue with step 13. But now listen carefully: Firstly I won’t host this file there forever, so if it’s gone it’s gone. Secondly I can’t promise it’ll work on your Mac. I’ve built it on an iMac running Mac OS X Lion 10.7.1 with PHP 5.3.6 and have also successfully tested the extension by copying it to a MacBook Air – so why shouldn’t it run on your Mac as well? But if it doesn’t (your Apache probably won’t start up then) you might have to build it yourself as described in this post.

    A tip for those following step 11: You might not have “wget” installed on your Mac. Use this command instead: curl -O http://pear.php.net/go-pear.phar

    If you have any comments, tweet me: @NewMancunian

    Nick — September 15, 2011

  12. If you are trying to install mongo with xampp see: http://php.net/manual/pt_BR/mongo.installation.php#mongo.installation.osx
    I had to download and extract manually the mongo.so file in my php extension directory. If you don’t know where is located your extension directory check on phpinfo() and place the mongo.so the extension directory.

    Mateus Gomes — December 11, 2011

  13. [...] already had MongoDB installed for years on my Mac, but I found this article recently and followed the instructions to setup a better install. Using these steps you can use OS X’s [...]

    Install MongoDB on OS X | blueleftistconstructor — July 21, 2012

  14. [...] can follow the directions from http://manas.tungare.name/blog/how-to-install-mongodb-for-php-on-mac-os-x/ at point [...]

    Set up PHP 5, Apache and MongoDB on OS X Lion 10.8 | Riccardo Coppola — September 30, 2012

  15. Great tutorial ;) Thank you a lot {Readed from Slovakia}

    Andrej Baran — October 18, 2012

  16. In your test script, “test” has to be quoted, since it is php ;)

    $collection->insert(array(“test” => ‘Test OK’));

    Christian Rosenhagen — September 3, 2013

  17. Thanks for the instructions. Everything worked until the very last part. I got this message:
    Fatal error: Class ‘Mongo’ not found in /Library/WebServer/Documents/mongodb.php on line 2

    Guillaume — March 12, 2014

  18. Not sure if this thread is still alive, but I found what was missing from these instructions for Mavericks from Rob Allen. Here it is just in case someone finds themselves with the problem I had:

    php.ini

    cd /etc
    sudo cp php.ini.default php.ini
    sudo chmod ug+w php.ini
    sudo chgrp staff php.ini
    Edit php.ini and change settings appropriately.
    At a minimum, you should change:
    date.timezone = “Europe/London”
    error_reporting = E_ALL
    display_errors = On
    html_errors = On
    extension_dir = “/usr/lib/php/extensions/no-debug-non-zts-20100525″

    Guillaume — March 13, 2014

Leave a comment

 

Popular Posts