doudu2515 2015-08-25 13:56
浏览 315
已采纳

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

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!

  • 写回答

1条回答 默认 最新

  • 普通网友 2015-08-26 10:37
    关注

    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]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog