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

def average(self, field):

    db_field = self._fields_to_dbfields([field]).pop()
    pipeline = [{'$match': self._query}, {'$group': {'_id': 'avg', 'total': {'$avg': ('$' + db_field)}}}]
    ListField = _import_class('ListField')
    field_parts = field.split('.')
    field_instances = self._document._lookup_field(field_parts)
    if isinstance(field_instances[(-1)], ListField):
        pipeline.insert(1, {'$unwind': ('$' + field)})
    result = self._document._get_collection().aggregate(pipeline)
    if IS_PYMONGO_3:
        result = tuple(result)
    else:
        result = result.get('result')
    if result:
        return result[0]['total']
    return 0
