how can i populate in pymongo?

Viewed 3524
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))

here i'm doing cron job and want to send push notification. so i need to use two collections for that.

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

in this line i get date from booking and

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

in this line within for loop i'm getting user who booked that booking then next

booking_id=data["_id"]

in this line of the loop i'm getting booking id from above used booking collection. all are working but it's slow. i don't like this. i want reduce these two collections finding steps. i tried so many ways i can't able to optimize those two lines. is there any solution to reduce these ?

1 Answers

You can use the nosql approach and store user data with bookings and directly get token from bookings data only

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))

Or you can avoid multiple find_one and do only one find query like below, avoiding multiple DB calls

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))
Related