aggregate_sum/average + unit tests
This commit is contained in:
@@ -1248,6 +1248,23 @@ class BaseQuerySet(object):
|
||||
else:
|
||||
return 0
|
||||
|
||||
def aggregate_sum(self, field):
|
||||
"""Sum over the values of the specified field.
|
||||
|
||||
:param field: the field to sum over; use dot-notation to refer to
|
||||
embedded document fields
|
||||
|
||||
This method is more performant than the regular `sum`, because it uses
|
||||
the aggregation framework instead of map-reduce.
|
||||
"""
|
||||
result = self._document._get_collection().aggregate([
|
||||
{ '$match': self._query },
|
||||
{ '$group': { '_id': 'sum', 'total': { '$sum': '$' + field } } }
|
||||
])
|
||||
if result['result']:
|
||||
return result['result'][0]['total']
|
||||
return 0
|
||||
|
||||
def average(self, field):
|
||||
"""Average over the values of the specified field.
|
||||
|
||||
@@ -1303,6 +1320,23 @@ class BaseQuerySet(object):
|
||||
else:
|
||||
return 0
|
||||
|
||||
def aggregate_average(self, field):
|
||||
"""Average over the values of the specified field.
|
||||
|
||||
:param field: the field to average over; use dot-notation to refer to
|
||||
embedded document fields
|
||||
|
||||
This method is more performant than the regular `average`, because it
|
||||
uses the aggregation framework instead of map-reduce.
|
||||
"""
|
||||
result = self._document._get_collection().aggregate([
|
||||
{ '$match': self._query },
|
||||
{ '$group': { '_id': 'avg', 'total': { '$avg': '$' + field } } }
|
||||
])
|
||||
if result['result']:
|
||||
return result['result'][0]['total']
|
||||
return 0
|
||||
|
||||
def item_frequencies(self, field, normalize=False, map_reduce=True):
|
||||
"""Returns a dictionary of all items present in a field across
|
||||
the whole queried set of documents, and their corresponding frequency.
|
||||
|
||||
Reference in New Issue
Block a user