Database Reference
In-Depth Information
//Print the result
while($document = $cursor->getNext())
{
print_r($document);
}
Finally, you can use the skip() function to skip the first n results that match your criteria. This function also
works on a cursor:
// Connect to the database
$c = new MongoClient();
// Select the collection 'people' from the database 'contacts'
$collection = $c->contacts->people;
// Execute the query and store it under the $cursor variable
$cursor = $collection->find();
// Use the skip function to skip the first result found
$cursor->skip(1);
// Print the result
while($document = $cursor->getNext())
{
print_r($document);
}
Counting the Number of Matching Results
You can use PHP's count() function to count the number of documents matching your criteria and return the number
of items in an array. This function is part of the MongoCursor class and thus operates on the cursor. The following
example shows how to get a count of contacts in the collection for people who live in the United States:
// Connect to the database
$c = new MongoClient();
// Select the collection 'people' from the database 'contacts'$collection = $c->contacts->people;
// Specify the search parameters
$country = array("Address.Country" => "USA");
// Execute the query and store under the $cursor variable for further processing
$cursor = $collection->find($country);
// Count the results and return the value
print_r($cursor->count());
This query returns one result. Such counts can be useful for all sorts of operations, whether it's counting
comments, the total number of registered users, or anything else.
Grouping Data with the Aggregation Framework
The aggregation framework is easily one of the more powerful features built into MongoDB, as it allows you to calculate
aggregated values without needing to use the—often overly complex—Map/Reduce functionality. One of the most
useful pipeline operators the framework includes is the $group operator, which can loosely be compared to SQL's
GROUP BY functionality. This operator allows you to calculate aggregate values based upon a collection of documents.
For example, the aggregation function $max can be used to find and return a group's highest value; the $min function to
find and return the lowest value, and $sum to calculate the total number of occurrences of a given value.
 
Search WWH ::




Custom Search