MongoDB - 从一系列日期获取每天注册和确认用户的计数

时间:2016-09-27 20:33:48

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

我的Users集合具有以下结构:

{
    ...
    createdAt: Date,
    confirmedAt: Date // can be null, meaning the user had not confirmed his e-mail
}

createdAt保留用户在网站上注册的日期,confirmedAt保留用户确认其电子邮件的日期。

我可以查询特定日期并获取用户总数以及当天有多少用户未确认其电子邮件:

db.users.aggregate([{
    $match: {
        createdAt: {
            "$lte": ISODate("2016-09-28")
        }
    }
}, {
    $group: {
        _id: ISODate("2016-09-28"),
        total: {
            $sum: 1
        },
        inactive: {
            $sum: {
                $cond: [{
                    $or: [{
                        $eq: ["$confirmedAt", null]
                    }, {
                        $gt: ["$confirmedAt", ISODate("2016-09-28")]
                    }]
                }, 1, 0]
            }
        }
    }
}])

这会产生如下结果:

{ 
    "_id" : ISODate("2016-09-28T00:00:00.000+0000"), 
    "total" : NumberInt(11904), 
    "inactive" : NumberInt(1328)
}

我需要的是获得日期范围的结果,而不必为每个日期重复查询。

这将是我追求的结果:

[{ 
    "_id" : ISODate("2016-09-28T00:00:00.000+0000"), 
    "total" : NumberInt(11904), 
    "inactive" : NumberInt(1328)
},{ 
    "_id" : ISODate("2016-09-27T00:00:00.000+0000"), 
    "total" : NumberInt(11883), 
    "inactive" : NumberInt(1314)
},{ 
    "_id" : ISODate("2016-09-26T00:00:00.000+0000"), 
    "total" : NumberInt(11852), 
    "inactive" : NumberInt(1311)
}]

PS:您不必使用mongo的聚合框架。如果你可以使用map-reduce来做到这一点我很好。也可以使用猫鼬。

  • 建议的副本不回答我的问题。通过按“天”字段分组,$ sum将仅适用于当天的数字。我需要计算从开始到该范围内每个日期注册的用户数。

0 个答案:

没有答案