def get_vote_avg(cls): avgCursor = cls.blogItemCollection.aggregate([{ '$group': { '_id': '$source', 'avgVote': { '$avg': "$vote" } } }]) avgList = list(avgCursor) avg = SON.to_dict(avgList[0])['avgVote'] return avg
def get_start_article_url(cls): """get the last article url from mongodb 算法是随机选取当前文章中被赞数大于平均值的一个文章的url """ # match = {'$group': {'_id': "$_id", 'vote': {'$max': "$vote"}}} # max = cls.blogItemCollection.aggregate([match]) maxCursor = cls.blogItemCollection.find({}, { "vote": 1, '_id': 0 }).sort('vote', -1).limit(1) maxVoteList = list(maxCursor) if maxVoteList.__len__() <= 0: # 数据库中尚未有数据 log.msg("there isn't any article in mongodb", level=log.DEBUG) return None max = SON.to_dict(maxVoteList[0])['vote'] avg = math.floor(cls.get_vote_avg()) articlesCursor = cls.blogItemCollection.find({"vote": {'$lte': max, '$gte': avg}}, {"id": 1, "vote": 1, '_id': 0})\ .sort('vote', -1).limit(3) articlesList = list(articlesCursor) index = randint(0, articlesList.__len__() - 1) article = SON.to_dict(articlesList[index]) return article['id']