This example shows how to use the map_reduce() method to perform map/reduce style aggregations on your data.

To start, we’ll insert some example data which we can perform map/reduce queries on:

Now we’ll define our map and reduce functions. In this case we’re performing the same operation as in the MongoDB Map/Reduce documentation - counting the number of occurrences for each tag in the tags array, across the entire collection.

Our map function just emits a single (key, 1) pair for each tag in the array:

>>> from bson.code import Code >>> map = Code ( "function () {" ... " this.tags.forEach(function(z) {" ... " emit(z, 1);" ... " });" ... "}" )

The reduce function sums over all of the emitted values for a given key:

>>> reduce = Code ( "function (key, values) {" ... " var total = 0;" ... " for (var i = 0; i < values.length; i++) {" ... " total += values[i];" ... " }" ... " return total;" ... "}" )

Note We can’t just return values.length as the reduce function might be called iteratively on the results of other reduce steps.

Finally, we call map_reduce() and iterate over the result collection: