How to get Today, Upcoming and Past Birthdays using MongoDB by passing days range like next 60 days Upcoming Birthdays or Past 60 days Birthdays etc.
We've saved user date of birth in the users collection with below json format.
"dob" : {
"year" : "2015",
"month" : "06",
"day" : "30"
},
"birthday" : ISODate("1975-08-26T18:30:00.000Z") // Correct date format
Basically my solution is here in the Right Answer but not clear how to use with my collection dataset.
Find whether someone got a birthday in the next 30 days with mongo
Thanks!
In the "users" collection birthday date should be stored as in below format:
"birthday" : ISODate("1975-08-26T18:30:00.000Z")
var today = new Date();
var m1 = { "$match" : { "birthday" : { "$exists" : true, "$ne" : '' } } };
var p1 = {
"$project" : {
"_id" : 0,
"username" : 1,
"birthday" : 1,
"todayDayOfYear" : { "$dayOfYear" : today },
"dayOfYear" : { "$dayOfYear" : "$birthday" }
}
};
var p2 = {
"$project" : {
"username" : 1,
"birthday" : 1,
"daysTillBirthday" : { "$subtract" : [
{ "$add" : [
"$dayOfYear",
{ "$cond" : [{"$lt":["$dayOfYear","$todayDayOfYear"]},365,0 ] }
] },
"$todayDayOfYear"
] }
}
};
if ( showcase == 'today' ) {
var m2 = { "$match" : { "daysTillBirthday" : { "$lt" : 1 } } }; // lt:1 = Today Birthdays
} else if ( showcase == 'upcoming' ) {
var m2 = { "$match" : { "daysTillBirthday" : { "$lt" : 60 } } }; // lt:60 = Next 60 days Upcoming Birthdays
} else if ( showcase == 'past' ) {
var m2 = { "$match" : { "daysTillBirthday" : { "$gt" : 60 } } }; // gt = Past 60 days Birthdays
}
db.users.aggregate([m1, p1, p2, m2]);