我刚刚开始学习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")
}
最佳答案
要获取当月生日的所有用户的列表,您需要运行使用 $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
返回的系统变量 基于 $month
date operator并丢弃文档,否则使用 $$PRUNE
。
关于node.js - 选择当月生日的所有用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42436765/