select当月有生日的所有用户

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

我需要select当月有生日的所有用户


用户架构:

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") } 

要获取当月所有生日的用户列表,您需要运行一个使用$redactpipe道的集合操作,在$cond操作符的帮助下过滤文档以执行编辑。 考虑执行以下pipe道:

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

上面的$condexpression式

 "$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 } 

$redactpipe道将根据$month date操作符返回所有与$cond返回的$$KEEP系统variables相匹配的文档,否则放弃$$PRUNE文档。

如果你有inputdate,即从date和toDate,简单的查询是:

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