我有一组用户。所有用户都有一个createdAt和一个lastLogin字段。createdAt字段表示用户注册时的日期,而lastLogin字段是用户最后一次登录站点的日期。
我想知道有多少用户在2月份注册后至少30天再次登录到该网站。更重要的是,我想知道有多少用户在3月,4月,5月等注册后,至少30天后,他们第一次注册。
我有一个类似的(但不同的)方法,它计算出在过去30天内每个月有多少人登录( fromDate是30天前的):
const pipeline = [
{
$match: {
lastLogin: {
$gt: fromDate,
$exists: true
},
},
},
{
$group: {
_id: {
year : { $year : "$createdAt" },
month : { $month : "$createdAt" },
},
sum: { $sum: 1 }
}
}
];但我不知道该怎么做才能做我想做的事。
我想要做的是统计一下在3月1日之后的任何时间点,有多少人注册了2月1日。第二个问题是统计2月份注册的人数在过去30天中注册的人数。因此,如果今天是10月1日,那么从9月1日到10月1日签署的每个人都会被计算在内。
发布于 2016-11-29 11:55:50
尝试使用map-还原查询,我认为这是您需要的:
// Al 3 users were createdAt februrary 2016
db.collection.save([
{createdAt: new Date(2016, 1, 2), lastLogin: new Date(2016, 2, 5)},
{createdAt: new Date(2016, 1, 3), lastLogin: new Date(2016, 2, 7)},
{createdAt: new Date(2016, 1, 2), lastLogin: new Date(2016, 1, 15)},
])
map = function() {
var days30after = new Date(this['createdAt']);
days30after.setDate(this['createdAt'].getDate()+30);
if(this['lastLogin'] >= days30after){
// Group results based on year and month values, add 1 to month
var key = {'year':this['createdAt'].getUTCFullYear(), 'month':this['createdAt'].getUTCMonth()+1};
emit(key, 1);
}
}
reduce = function(key, values) {
return values.length;
}
db.collection.mapReduce(map,reduce, { out : "collection2" });
db.collection2.find().pretty()结果:2名用户在2月份注册,30天后再次登录。
{ "_id" : { "year" : 2016, "month" : 2 }, "value" : 2 }https://stackoverflow.com/questions/40860969
复制相似问题