Database Reference
In-Depth Information
Let's say that you want to get a list of all contacts in your collection, grouped by the country where they live.
The aggregation framework lets you do this easily. Let's take a look at an example:
// 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 $result variable
$result = $collection->aggregate(array(
'$group' => array(
'_id' => '$Address.Country',
'total' => array('$sum' => 1)
)
));
// Count the results and return the value
print_r($result);
As you can see, the aggregate function accepts one (or more) arrays with pipeline operators (in this case, the
$group operator). Here, you can specify how the resulting output is returned, and any optional aggregation functions
to execute: in this case the $sum function. In this example a unique document is returned for every unique country
found, represented by the document's _id field. Next, the total count of each country is summarized using the $sum
function, and returned using the total field. Note that the $sum function is represented by an array, and given the
value of 1 as we want every match to increase the total by 1.
You might wonder what the resulting output will look like. Here's an example of the output, given that there are
two contacts living in the United Kingdom and one in the United States:
Array (
[result] => Array (
[0] => Array (
[_id] => UK [total] => 2
)
[1] => Array (
[_id] => USA [total] => 1
)
)
[ok] => 1
)
This example is but a simple one, but the aggregation framework is quite powerful indeed, as you will see when
we look into it more closely in Chapter 8.
Specifying the Index with Hint
You use PHP's hint() function to specify which index should be used when querying for data; doing so can help
you increase query performance. For instance, assume you have thousands of contacts in your collection, and you
generally search for a person based upon last name. In this case, it's recommended that you create an index on the
Last Name key in the collection.
Note
the hint() example shown next will not return anything if no index is created first.
 
 
Search WWH ::




Custom Search