在MongoDB中逐日查询总用户数

mTu*_*ran 3 mongoose mongodb

我有“用户”集合,我想要每天的总用户数,例如:

01.01.2012 -> 5
02.01.2012 -> 9
03.01.2012 -> 18
04.01.2012 -> 24
05.01.2012 -> 38
06.01.2012 -> 48
Run Code Online (Sandbox Code Playgroud)

我为每个用户创建了 attritube。你能帮我查询一下吗?

{ 
  "_id" : ObjectId( "5076d3e70546c971539d9f8a" ),
  "createdAt" : Date( 1339964775466 ),
  "points" : 200,
  "profile" : null,
  "userId" : "10002"
}
Run Code Online (Sandbox Code Playgroud)

Vin*_*dya 5

这是适用于每天计数的数据

我得到的输出:

30/3/2016   4
26/3/2016   4
21/3/2016   4
12/3/2016   12
14/3/2016   18
10/3/2016   10
9/3/2016    11
8/3/2016    19
7/3/2016    21
Run Code Online (Sandbox Code Playgroud)

脚本:

model.aggregate({
  $match: {
    createdAt: {
      $gte: new Date("2016-01-01")
    } 
  } 
}, { 
  $group: {
    _id: { 
      "year":  { "$year": "$createdAt" },
      "month": { "$month": "$createdAt" },
      "day":   { "$dayOfMonth": "$createdAt" }
    },
    count:{$sum: 1}
  }
}).exec(function(err,data){
  if (err) {
    console.log('Error Fetching model');
    console.log(err);
  } else {
    console.log(data);
  }
});
Run Code Online (Sandbox Code Playgroud)