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)
| 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 |