'This method makes use of the aggregation framework to
produce top values for a given field.
If `distinct` is True (default), the top values are computed
by distinct events. If it is False, they are computed based on
the "count" field.'

def topvalues(self, field, flt=None, topnbr=10, sort=None, limit=None, skip=None, least=False, distinct=True):

    if isinstance(field, basestring):
        field = self.fields[field]
    outputproc = None
    if (flt is None):
        flt = PassiveFilter()
    base = flt.query(select([Passive.id]).select_from(flt.select_from)).cte('base')
    order = ('count' if least else desc('count'))
    req = flt.query(select([(func.count() if distinct else func.sum(Passive.count)).label('count'), field]).select_from(flt.select_from).group_by(field))
    if (outputproc is None):
        outputproc = (lambda val: val)
    return ({'count': result[0], '_id': outputproc((result[1:] if (len(result) > 2) else result[1]))} for result in self.db.execute(req.order_by(order).limit(topnbr)))
