pymongo

1.python连接mongodb

mongo_uri = "mongodb://xxx:xxx@xxx.xxx.xxx.xxx:27017/mychat"             
client = MongoClient(mongo_uri) 
db = client['wechat']    

bson生成ObjectId字符串

demoid = bson.ObjectId()    
str = demoid.__str__()

多条件组合group,match要作为第一个参数才能赛选
db.comment.aggregate([{$match:{"time.create":{$gt:1562515200000}}},{ $group: { _id: {user :"$user", no: "$no"}, countA: { $sum: 1}}}, {$sort:{countA:-1}}, { "$limit": 10 }])

对应的python代码

aggs = [

            {"$match":{"time.create":{"$gt":self.timeCheckFrom * 1000}}},

            #{"$project": {"field3":1, "field4":1}},

            {"$group": { "_id": {"user" :"$user", "no": "$no"}, "countA": { "$sum": 1}}},

            {"$sort":{"countA" : -1}}, 

            { "$limit": 5 }

        ]

        results = self.db.comment.aggregate(aggs)

        index = 0

        for item in results:

2.DBRef (user字段是一个DBRef)

在mongo命令中,直接使用$user就可以了,不能user.$id,

在python中直接是 user.id,user不是字典,不能user.get('id')

 

# coding=utf-8

import pymongo

from pymongo import ASCENDING, DESCENDING

from bson.dbref import DBRef

from bson import ObjectId

import six

import collections

import time

import datetime

import calendar

from base import *

from __builtin__ import list

 

 

def first_day_of_week():

    now = int(time.time())

    time_str = time.strftime("%Y-%m-%d %w", time.localtime(now))

    t, day = time_str.split(" ")

    day_cur = time.mktime(time.strptime(t, '%Y-%m-%d'))

    first_day = day_cur - (int(day) - 1) * 24 * 3600

    return int(first_day)

        

 

 

class List:

    db = mongo_proxy    

    

    def __init__(self):

        self.timeCheckFrom = first_day_of_week()

    

    

    

#     def timestamp_format(self, timestamp):

#         """将10位(s)时间戳格式化"""

#         format = '%Y-%m-%d'

#         return time.strftime(format, time.localtime(timestamp))

    

    #点赞最多的

    def FeedLiked(self):

        name = "rank_feed_like_" + str(self.timeCheckFrom)

        api_redis_client.delete(name)

        sort_condition = [("stat.like",-1)]

        condition = {'time.create': {'$gt': self.timeCheckFrom * 1000}, 'room.$id' : {'$ne' : ObjectId("100000000000000000000000")}}

        results = self.db.feed.find(condition).sort(sort_condition).limit(5)

        listFeeds = []

        index = 0

        for item in results:

            index += 1

            dictFeed = {}

            no = item.get("no")            

            userid = item.get("user").id

            feedid = str(item.get("_id"))

            listFeeds.append(dictFeed)

            key = str(userid) + "_" + str(no) + "_" + str(index)

            api_redis_client.hset(name, key, feedid)     

            

    #被回复最多的帖子

    def RankFeedComment(self):

        name = "rank_feed_comment_" + str(self.timeCheckFrom)

        api_redis_client.delete(name)

        sort_condition = [("stat.comment", -1)]

        condition = {'time.create': {'$gt': self.timeCheckFrom * 1000}, 'room.$id' : {'$ne' : ObjectId("100000000000000000000000")}}

        results = self.db.feed.find(condition).sort(sort_condition).limit(5)

        listFeeds = []

        index = 0

        for item in results:

            index += 1

            dictFeed = {}

            no = item.get("no")            

            userid = item.get("user").id

            feedid = str(item.get("_id"))

            listFeeds.append(dictFeed)

            key = str(userid) + "_" + str(no) + "_" + str(index)

            api_redis_client.hset(name, key, feedid)  

        

        

        return True

    

    #

    def RankCommentFeed(self):

        name = "rank_comment_feed_" + str(self.timeCheckFrom)

        api_redis_client.delete(name)

        

        aggs = [

            {"$match":{"time.create":{"$gt":self.timeCheckFrom * 1000}}},

            #{"$project": {"field3":1, "field4":1}},

            {"$group": { "_id": {"user" :"$user", "no": "$no"}, "countA": { "$sum": 1}}},

            {"$sort":{"countA" : -1}}, 

            { "$limit": 5 }

        ]

 

        results = self.db.comment.aggregate(aggs)

        index = 0

        for item in results:

            index += 1

            dictFeed = {}

            no = item.get("_id").get('no')            

            userid = item.get("_id").get('user').id

            num = item.get("countA")

                       

            key = str(userid) + "_" + str(no) + "_" + str(index)

            api_redis_client.hset(name, key, num)       

        

        return True

    

    #xxx 交际广泛,新加了10个好友    

    def RankMakeFriends(self):

        name = "rank_make_friends_" + str(self.timeCheckFrom)

        api_redis_client.delete(name)

        

        aggs = [

            {"$match":{"time.create":{"$gt":self.timeCheckFrom * 1000}}},

            #{"$project": {"field3":1, "field4":1}},

            {"$group": { "_id": {"user" :"$user", "no": "$no"}, "countA": { "$sum": 1}}},

            {"$sort":{"countA" : -1}}, 

            { "$limit": 5 }

        ]       

 

        results = self.db.friend.aggregate(aggs)

        index = 0

        for item in results:

            index += 1

            dictFeed = {}

            no = item.get("_id").get('no')            

            userid = item.get("_id").get('user').id

            num = item.get("countA")

                       

            key = str(userid) + "_" + str(no) + "_" + str(index)

            api_redis_client.hset(name, key, num)       

        

    

 

    def RankCreateFeed(self):

        name = "rank_create_feed_" + str(self.timeCheckFrom)

        api_redis_client.delete(name)

        

        aggs = [

            {"$match":{"time.create":{"$gt":self.timeCheckFrom * 1000}}},

            #{"$project": {"field3":1, "field4":1}},

            {"$group": { "_id": {"user" :"$user", "no": "$no"}, "countA": { "$sum": 1}}},

            {"$sort":{"countA" : -1}}, 

            { "$limit": 5 }

        ]       

 

        results = self.db.feed.aggregate(aggs)

        index = 0

        for item in results:

            index += 1

            dictFeed = {}

            no = item.get("_id").get('no')            

            userid = item.get("_id").get('user').id

            num = item.get("countA")

                       

            key = str(userid) + "_" + str(no) + "_" + str(index)

            api_redis_client.hset(name, key, num)       

        

        return True

 

if __name__ == '__main__':

    

    myList = List() 

#     myList.FeedLiked()

#     myList.RankFeedComment()

    #myList.RankCommentFeed()

    #myList.RankCreateFeed()

    myList.RankMakeFriends()

    

    

    print "task finished------------------"

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值