MCPcopy Index your code
hub / github.com/MongoEngine/mongoengine / average

Method average

mongoengine/queryset/base.py:1590–1614  ·  view source on GitHub ↗

Average over the values of the specified field. :param field: the field to average over; use dot notation to refer to embedded document fields

(self, field)

Source from the content-addressed store, hash-verified

1588 return 0
1589
1590 def average(self, field):
1591 """Average over the values of the specified field.
1592
1593 :param field: the field to average over; use dot notation to refer to
1594 embedded document fields
1595 """
1596 db_field = self._fields_to_dbfields([field]).pop()
1597 pipeline = [
1598 {"$match": self._query},
1599 {"$group": {"_id": "avg", "total": {"$avg": "$" + db_field}}},
1600 ]
1601
1602 # if we're performing an average over a list field, we average out
1603 # all the elements in the list, hence we need to $unwind the arrays
1604 # first
1605 ListField = _import_class("ListField")
1606 field_parts = field.split(".")
1607 field_instances = self._document._lookup_field(field_parts)
1608 if isinstance(field_instances[-1], ListField):
1609 pipeline.insert(1, {"$unwind": "$" + field})
1610
1611 result = tuple(self._document._get_collection().aggregate(pipeline))
1612 if result:
1613 return result[0]["total"]
1614 return 0
1615
1616 def item_frequencies(self, field, normalize=False, map_reduce=True):
1617 """Returns a dictionary of all items present in a field across

Callers 5

test_averageMethod · 0.80
test_embedded_averageMethod · 0.80
test_array_averageMethod · 0.80

Calls 7

_fields_to_dbfieldsMethod · 0.95
_import_classFunction · 0.90
popMethod · 0.80
_lookup_fieldMethod · 0.80
insertMethod · 0.80
aggregateMethod · 0.80
_get_collectionMethod · 0.80

Tested by 5

test_averageMethod · 0.64
test_embedded_averageMethod · 0.64
test_array_averageMethod · 0.64