def get_stat_by_groups(self, course=None, faculty=None, department=None):
    group = {'$group': {'_id': '$group', 'avg_total_words': {'$avg': '$words.total_words'}, 'avg_unique_words': {'$avg': '$words.total_unique_words'}, 'avg_persent_unique_words': {'$avg': '$words.persent_unique_words'}, 'total_reports_loaded': {'$sum': 1}}}
    sort = {'$sort': {'_id': 1}}
    if ((not course) and (not faculty) and (not department)):
        return self.db['reports'].aggregate([group, sort])
    if (course and (not faculty) and (not department)):
        match = {'$match': {'course': course}}
    elif (faculty and (not course) and (not department)):
        match = {'$match': {'faculty': faculty}}
        sort['$sort']['faculty'] = 1
    elif (department and (not course) and (not faculty)):
        match = {'$match': {'department': department}}
        sort['$sort']['department'] = 1
    elif ((course and faculty) or (course and department) or (faculty and department)):
        match_list = []
        if course:
            match_list.append({'course': course})
        if faculty:
            match_list.append({'faculty': faculty})
            sort['$sort']['faculty'] = 1
        if department:
            match_list.append({'department': department})
            sort['$sort']['department'] = 1
        match = {'$match': {'$and': match_list}}
    return self.db['reports'].aggregate([match, group, sort])
def get_stat_by_groups(self, course=None, faculty=None, department=None):
    group = {'$group': {'_id': '$group', 'avg_total_words': {'$avg': '$words.total_words'}, 'avg_unique_words': {'$avg': '$words.total_unique_words'}, 'avg_persent_unique_words': {'$avg': '$words.persent_unique_words'}, 'total_reports_loaded': {'$sum': 1}}}
    sort = {'$sort': {'_id': 1}}
    if ((not course) and (not faculty) and (not department)):
        return self.db['reports'].aggregate([group, sort])
    if (course and (not faculty) and (not department)):
        match = {'$match': {'course': course}}
    elif (faculty and (not course) and (not department)):
        match = {'$match': {'faculty': faculty}}
        sort['$sort']['faculty'] = 1
    elif (department and (not course) and (not faculty)):
        match = {'$match': {'department': department}}
        sort['$sort']['department'] = 1
    elif ((course and faculty) or (course and department) or (faculty and department)):
        match_list = []
        if course:
            match_list.append({'course': course})
        if faculty:
            match_list.append({'faculty': faculty})
            sort['$sort']['faculty'] = 1
        if department:
            match_list.append({'department': department})
            sort['$sort']['department'] = 1
        match = {'$match': {'$and': match_list}}
    return self.db['reports'].aggregate([match, group, sort])