Small MongoDB Notes

From PaskvilWiki
Revision as of 16:49, 1 April 2013 by Admin (Talk | contribs)

Jump to: navigation, search

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();