How can I query a database of users with their birthdays stored as a Date for the users with upcoming birthdays?
For example if a user is stored as:
name : "John Doe"
birthday : 1980-06-30T00:00:00.000 00:00
and their birthday is within a month, how do I retrieve it?
I have tried this in pymongo but it only returns people with their birthdays exactly today and one month from now.
find({
"$and": [
{"$and": [
{"$expr": {"$gte": [{"$month": "$birthday"}, today.month]}},
{"$expr": {"$gte": [{"$dayOfMonth": "$birthday"}, today.day]}}
]},
{"$and": [
{"$expr": {"$lte": [{"$month": "$birthday"}, one_month_from_today.month]}},
{"$expr": {"$lte": [{"$dayOfMonth": "$birthday"}, one_month_from_today.day]}}
]}
]
})
CodePudding user response:
I needed to make it so it found all days where (month == today.month && day >= today.day) || (month == one_month_from_today.month && day <= one_month_from_today.day)
CodePudding user response:
Try to change your filter like this:
find({
"$or": [
{"$and": [
{"$expr": {"$eq": [{"$month": "$birthday"}, today.month]}},
{"$expr": {"$gte": [{"$dayOfMonth": "$birthday"}, today.day]}}
]},
{"$and": [
{"$expr": {"$eq": [{"$month": "$birthday"}, one_month_from_today.month]}},
{"$expr": {"$lte": [{"$dayOfMonth": "$birthday"}, one_month_from_today.day]}}
]}
]
})