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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?