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

Method sum

mongoengine/queryset/base.py:1564–1588  ·  view source on GitHub ↗

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

(self, field)

Source from the content-addressed store, hash-verified

1562 return queryset
1563
1564 def sum(self, field):
1565 """Sum over the values of the specified field.
1566
1567 :param field: the field to sum over; use dot notation to refer to
1568 embedded document fields
1569 """
1570 db_field = self._fields_to_dbfields([field]).pop()
1571 pipeline = [
1572 {"$match": self._query},
1573 {"$group": {"_id": "sum", "total": {"$sum": "$" + db_field}}},
1574 ]
1575
1576 # if we're performing a sum over a list field, we sum up all the
1577 # elements in the list, hence we need to $unwind the arrays first
1578 ListField = _import_class("ListField")
1579 field_parts = field.split(".")
1580 field_instances = self._document._lookup_field(field_parts)
1581 if isinstance(field_instances[-1], ListField):
1582 pipeline.insert(1, {"$unwind": "$" + field})
1583
1584 result = tuple(self._document._get_collection().aggregate(pipeline))
1585
1586 if result:
1587 return result[0]["total"]
1588 return 0
1589
1590 def average(self, field):
1591 """Average over the values of the specified field.

Callers 5

test_sumMethod · 0.80
test_embedded_sumMethod · 0.80
test_array_sumMethod · 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_sumMethod · 0.64
test_embedded_sumMethod · 0.64
test_array_sumMethod · 0.64