node.js - 选择当月生日的所有用户

标签 node.js mongodb mongoose mongodb-query aggregation-framework

我刚刚开始学习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/

相关文章:

javascript 方法链接 - knex.js

javascript - 如何将 mvc 方法应用于 Nodejs - Express 应用程序中的 app.js 文件

node.js - Mongoose:在保存时根据父字段值设置子文档字段值

javascript - 尝试使用 Mongoose 和异步保存到数据库时出现多个错误

node.js - 如何在nodejs v6.11.3中使用 "import"

node.js - sails js 数据关系

node.js - 幻 Node 模块无法加载外部资源

ruby-on-rails - 为什么我的 mongoDB 托管 mongoid.yml 的 uri 设置无法正常工作?

mongodb - 如何在 mongoDB 中使用服务器端 Javascript 终止所有应用程序查询?

javascript - 如何删除 Mongoose 模式中的引用值