提问者:小点点

选择当月有生日的所有用户


我刚刚开始学习NodeJs MongoDB(Mongoose)。查询有问题。

我需要选择所有用户,谁在当月生日。

用户架构:

const UserSchema = new mongoose.Schema({
    email: {
        type: String,
        unique: true,
        required: true,
        index: true
    },
    password: {
        type: String,
        required: true
    },
    firstName: {
        type: String,
        required: true
    },
    lastName: {
        type: String,
        required: true
    },
    phone: {
        type: String,
        required: true
    },
    birthday: {
        type: Date,
        required: true
    },
    photo: {
        type: String,
        required: false
    },
    updated: {
        type: Date,
        default: Date.now
    }
});

集合(用户)文档示例:

{ 
    "__v" : NumberInt(0), 
    "_id" : ObjectId("589b26ab4490e29ab5bdc17c"), 
    "birthday" : ISODate("1982-08-17T00:00:00.000+0000"), 
    "email" : "test@gmail.com", 
    "firstName" : "John", 
    "lastName" : "Smith", 
    "password" : "$2a$10$/NvuIGgAYbFIFMMFW1RbBuRGvIFa2bOUQGMrCPRWV7BJtrU71PF6W", 
    "phone" : "1234567890", 
    "photo" : "photo-1486565456205.jpg", 
    "updated" : ISODate("2017-02-08T14:09:47.215+0000")
}

共2个答案

匿名用户

要获取当月生日的所有用户列表,需要运行聚合操作,该操作使用$redact管道在$cond运算符的帮助下过滤文档进行编辑。考虑执行以下管道:

User.aggregate([
    {
        "$redact": {
            "$cond": [
                {
                    "$eq": [
                        { "$month": "$birthday" },
                        { "$month": new Date() }
                    ]
                }
            ],
            "$$KEEP",
            "$$PRUNE"
        }
    }
]).exec(function(err, docs){
    if (err) throw err;
    console.log(docs);
});

上面的$cond表达式

"$cond": [
    {
        "$eq": [
            { "$month": "$birthday" },
            { "$month": new Date() }
        ]
    }
],

本质上表示条件语句

if (birthday.getMonth() === (new Date()).getMonth()) {
    "$$KEEP" // keep the document in the pipeline
} else {
    "$$PRUNE" // prune/discard the document from the output
}

并且$redact管道将返回所有与$KEEP系统变量匹配的文档,该变量由$cond基于$月日期运算符返回,否则将使用$$PRUNE丢弃文档。

匿名用户

如果您有输入日期,即fromDate和toDate,则简单查询为:

db.collection.find({"birthday":{$gte: fromDate, $lte: toDate}});