Difference between revisions of "Small MongoDB Notes"

From PaskvilWiki
Jump to: navigation, search
(Created page with "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: <pre>// host de...")
 
Line 12: Line 12:
 
     ; // do your best here...</pre>
 
     ; // do your best here...</pre>
 
If you need only one document (or know that there is - at most - one), you can use <tt>findOne()</tt> function that returns the document directly.
 
If you need only one document (or know that there is - at most - one), you can use <tt>findOne()</tt> function that returns the document directly.
 +
 +
Some more useful functions:
 +
<pre>// make sure 'field' is indexed:
 +
$client->database->collection->ensureIndex('field');
 +
// get some information about the query:
 +
$client->database->collection->find([query])->explain();</pre>

Revision as of 16:49, 1 April 2013

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