Small MongoDB Notes
From PaskvilWiki
Installation - Ubuntu
MongoDB Inc. provides PPA source for Ubuntu. PECL provides native PHP driver.
$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10 $ echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list $ sudo apt-get update $ sudo apt-get install mongodb-10gen $ sudo apt-get install php-pear # if you don't have PECL yet $ sudo pecl install mongo # PECL will echo what to add to php.ini $ sudo vim /etc/php5/apache2/php.ini $ sudo service apache2 restart # restart apache to reload php settings
Troubles on Desktop
While it behaves well on servers, MongoDB has some peculiarities on desktop machines.
Here's a typical day in the desktop MongoDB user's life:
# check it's running $ ps aux | grep mongod 0 S user 22154 28201 0 80 0 - 1097 pipe_w 16:31 pts/9 00:00:00 grep mongod # not running, eh?... lets try manually... beware that mongo # can't find its own config files on desktop machines... $ sudo mongod --config /etc/mongodb.conf all output going to: /var/log/mongodb/mongodb.log # did it die? if not, you're lucky and you're ready to roll!... # otherwise, lets rock... log will most probably tell you that you # need to repair db because of unclean shutdown $ sudo mongod --config /etc/mongodb.conf --repair ... # now we should be able to start mongo $ sudo mongod --config /etc/mongodb.conf
And now you should have mongo running (and one terminal stuck with mongo... but who cares, it's not the olden days, where you had just one).
Using in PHP
The PHP's PECL driver provides a very neat and clean integration. Databases and collections within are accessed directly as if members of the (client) connection:
// host defaults to 'localhost', port defaults to 27017: $client = new MongoClient(["host[:port]"]); // access database directly - replace 'database' with DB's name: $client->database // as well as collection within the database: $client->database->collection // now lets find some documents in the collection: $client->database->collection->find([query]); // find() returns iterator, so just foreach through it: foreach ($client->database->collection->find([query]) as $id => $doc) ; // do your best here...
If you need only one document (or know that there is - at most - one), you can use findOne() function that returns the document directly.
Some more useful functions:
// make sure 'field' is indexed: $client->database->collection->ensureIndex('field'); // get some information about the query: $client->database->collection->find([query])->explain();