我怎么能在pymongo居住?

时间:2017-11-06 14:23:18

标签: python pymongo

def day():
message ="one day is remaining to take up your food"
nextday =datetime.now() + timedelta(days= 1)
nextdaydate= nextday.strftime('X%d/X%m/%Y').replace('X0','X').replace('X','')
bookingdata =db.booking.find({"$and":[{'date':nextdaydate},{'status':'confirmed'}]})
for data in bookingdata:
    user=db.users.find_one({'_id' : data["user"]},{"devicetoken":1})
    booking_id=data["_id"]
    sendremindpush(user["devicetoken"],str(booking_id),str(message))

这里我正在做cron工作并希望发送推送通知。所以我需要使用两个集合。

  

bookingdata = db.booking.find({" $ and":[{' date':nextdaydate},{' status':'确认'}]})

在这一行我从预订中获取日期和

  

user = db.users.find_one({' _id':data [" user"]},{" devicetoken":1})

在for循环中的这一行我得到的用户预订了那个预订然后

  

booking_id =数据[" _id"]

在这一循环中,我从上面使用的预订系列中获得了预订ID。一切正常,但速度很慢。我不喜欢这样。我想减少这两个集合找到步骤。 我尝试了很多方法,我能够优化这两条线。 有什么办法可以减少这些吗?

1 个答案:

答案 0 :(得分:1)

您可以使用nosql方法并将用户数据存储在预订中,并直接从预订数据中获取令牌

def day():
message ="one day is remaining to take up your food"
nextday =datetime.now() + timedelta(days= 1)
nextdaydate= nextday.strftime('X%d/X%m/%Y').replace('X0','X').replace('X','')
bookingdata =db.booking.find({"$and":[{'date':nextdaydate},{'status':'confirmed'}]})
for data in bookingdate:
    user = data['user']
    booking_id=data["_id"]
    sendremindpush(user["devicetoken"],str(booking_id),str(message))

或者你可以避免多个find_one,只做一个查找如下的查询,避免多个数据库调用

def day():
message ="one day is remaining to take up your food"
nextday =datetime.now() + timedelta(days= 1)
nextdaydate= nextday.strftime('X%d/X%m/%Y').replace('X0','X').replace('X','')
bookingdata = []
users = []
for booking in db.booking.find({"$and":[{'date':nextdaydate},{'status':'confirmed'}]}):
    bookingdata.append(booking)
    users.append(booking['user'])
user_device_token_mappings = dict([(u['_id'),u['devicetoken']) for u in db.users.find({'_id' : {'$in':users}},{"devicetoken":1})])

for data in bookingdate:
    booking_id=data["_id"]
    device_token = user_device_token_mappings[data["user"]]
    sendremindpush(device_token,str(booking_id),str(message))