MongoDB:如何使用MongoDB获取今天,即将到来和过去的生日列表?

时间:2015-08-25 13:56:16

标签: javascript php mysql mongodb

如何使用MongoDB获取今天,即将到来和过去的生日,通过接下来的60天即将到来的生日或过去的60天生日等等。

我们已在用户集合中以json格式保存了用户出生日期。

"dob" : {
    "year" : "2015",
    "month" : "06",
    "day" : "30"
},

"birthday" : ISODate("1975-08-26T18:30:00.000Z") // Correct date format

基本上我的解决方案在正确的答案中,但不清楚如何使用我的集合数据集。

Find whether someone got a birthday in the next 30 days with mongo

谢谢!

1 个答案:

答案 0 :(得分:0)

在“users”集合中,生日日期应按以下格式存储:

"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]);