我的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来做到这一点我很好。也可以使用猫鼬。