Grouping Results of Find Operations in Python ApplicationsWhen performing operations on large datasets in Python, grouping the results based on the distinct values of one or more fields in a document is often useful. This can be done in code after retrieving the documents, but it is much more efficient to have the MongoDB server do it for you as part of a single request that is already iterating though the documents.
In Python, to group the results of a query, you can use the group() method on the Collection object. The group request collects all the documents that match a query, adds a group object to an array based on distinct values of a set of keys, performs operations on the group objects, and returns the array of group objects.
The syntax for the group() methods follows:
- group({key, cond , initial, reduce, [finalize]})
复制代码The key, cond, and initial parameters are a Dictionary object that define the fields to use, query, and limit documents and initial value settings. The reduce and finalize methods are String objects that contain a string form of a JavaScript function that is run on the server to reduce and finalize the results. See Hour 9, “Utilizing the Power of Grouping, Aggregation, and Map Reduce,” for more information on these parameters.
For illustration, the following code implements a basic grouping by generating the key, cond, and initial objects and passing in a reduce function as a string:
- key = {'first' : True }cond = {'first' : 'a', 'size': 5}
- initial = {'count' : 0}
- reduce = "function (obj, prev) { prev.count++; }"
- results = collection.group(key, cond, initial, reduce)
复制代码The result from the group method is a List that contains the groupings. To illustrate the results, the following code displays the items in the group one at a time:
- for result in results:
- print (result)
复制代码