Database Reference
In-Depth Information
This returns the following results, neatly presented in descending order:
{
u'ok': 1.0,
u'result': [
{u'_id': u'Laptop', u'Totals': 4},
{u'_id': u'In Use', u'Totals': 3},
{u'_id': u'Development', u'Totals': 3},
{u'_id': u'Storage', u'Totals': 1},
{u'_id': u'Not used', u'Totals': 1}
]
}
In addition to the $sum pipeline expression, the $group pipeline operator also supports various others, some of
which are listed below:
$push : Creates and returns an array of all the values found in its group.
$addToSet : Creates and returns an array of all the unique values found in its group.
$first : Returns only the first value found in its group.
$last : Returns only the last value found in its group.
$max : Returns the highest value found in its group.
$min : Returns the lowest value found in its group.
$avg : Returns the average value found in its group.
In this example you've looked at the $group , $unwind , and $sort pipeline operators, but many more powerful
pipeline operators exist, such, as the $geoNear operator. The aggregation framework and its operators are discussed in
more detail in Chapters 4, 6, and 8.
Specifying an Index with hint()
You can use the hint() function to specify which index should be used when querying for data. Using this function
can help you improve the query's performance. In Python, the hint() function also executes on the cursor. However,
you should keep in mind that the hint name you specify in Python needs to be the same as the one you passed to the
create_index() function.
In the next example, you will create an index first, and then search for the data that specifies the index. Before you
can sort in ascending order, however, you will need to use the import() function to import the ASCENDING method.
Finally, you need to execute the create_index() function:
>>> from pymongo import ASCENDING
>>> collection.create_index([("ItemNumber", ASCENDING)])
u'ItemNumber_1'
>>> for doc in collection.find({"Location.Owner" : "Walker, Jan"}) .hint([("ItemNumber",
ASCENDING)]):
... doc
...
 
Search WWH ::




Custom Search