Small MongoDB Notes

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

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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.