【问题标题】:Select all users who have birthday in current month选择当月生日的所有用户
【发布时间】:2017-02-24 21:48:18
【问题描述】:

我刚开始学习 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")
}

【问题讨论】:

  • 重复。看看这个问题:Answer1

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


【解决方案1】:

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

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 丢弃文档。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 这永远不会起作用,因为您只过滤一年。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-24
    • 2022-07-19
    • 1970-01-01
    • 2019-08-08
    • 2017-07-19
    • 2022-01-02
    • 1970-01-01
    相关资源
    最近更新 更多