我已经完成了跟踪活动用户的功能,这些用户一直在使用我的应用程序并查看他们的进度 . 实际上,我已经制作了功能,以便对我的用户进行群组分析!

我的想法是(群组分析)选择时间段(例如2012年10月1日至2013年10月1日),在我的案例中将所有使用app的用户放在第一个月(2012年10月1日至01/11月/ 2012),然后在剩下的选定月份中确定他们的进展!(我的意思是“进步”,如果他们下个月使用app,如果他们进行活动)

所以,我做了这项工作的功能,但它太慢了......这是我的功能:

def query(self):
    start = fields['start'].value
    end = fields['end'].value
    start_month, start_year = start.month, start.year
    end_month, end_year = end.month + 1, end.year + 1
    col = self.db[self.__collection__]
    # we only follow users that were in the first month and
    # we have to filter those activities by month
    users_funnel = []
    data = []
    for dt in rrule(MONTHLY, dtstart=start, until=end):
        query = {
            "activities": {
                "$exists": 1
            },
            "activities.started": {
                "$exists": 1,
                "$type": MONGODB_DATE_TYPE,
                "$gte": dt,
                "$lt": datetime(dt.year + dt.month / 12, (dt.month % 12) + 1, 1)
            }
        }

        if users_funnel:
            query['_id'] = {"$in": users_funnel}

        pipeline = [
            {'$project': {
                '_id': 1,
                'first_name': 1,
                'last_name': 1,
                'email': 1,
                'activities': 1
            }},
            {'$unwind': "$activities"},
            {"$match": query},
            {'$group': {
                '_id': {"y": {'$year': "$activities.started"},
                        "m": {'$month': "$activities.started"}},
                'users': {'$addToSet': "$_id"},
                'activities_count': {"$sum": 1},
                'users_data': {"$addToSet": {
                    "_id": "$_id",
                    "first_name": "$first_name",
                    "last_name": "$last_name"}}
            }},
            {"$sort": {
                "_id.y": 1,
                "_id.m": 1
            }}
        ]
        results = col.aggregate(pipeline)
        result = results.get("result", [])
        if result:
            data.append(result[0])
            users_funnel = result[0]['users']
    return data

然后我有 Cohort analysis 这样的图graph .

问题是关于我所做的那个功能太慢了 . 我需要更好的解决方案

任何可以帮助我开发在python中查询mongodb的群组分析功能???