我有一个这样的模型:
型号:

createdAt: {
 type: String,
 default: Moment(new Date()).format('YYYY-MM-DD')
},
loginTrack: [
{
  user_id: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Users',
  }
}

有了一些数据:
[
 {
  _id: ...,
  createdAt : '2018-03-22',
  loginTrack: [
   {user_id : 1,...}
   {user_id : 1, ...},
   {user_id : 2, ...}
  ]
 },
 {
   _id: ...,
   createdAt : '2018-03-23',
   loginTrack : [
     {user_id : 4, ...},
     {user_id : 1, ...}
   ]
  },
 {
  _id : ...,
  createdAt: '2018-03-24',
  loginTrack : [
   {user_id : 2, ...}
  ]
 ]

我想得到每天唯一新会话总数的百分比,这意味着计算前一天的会话数,MongoDB是否可以?
有这样的输出
[{
  date : '2018-03-22',
  newSessionsAvg : 2 (unique sessions only : maybe it's 100 % ?)
},
{
  date : '2018-03-23',
  newSessionAvg: 100
},
{
  date : '2018-03-24',
  newSessionAvg : 25 (1/ (2+2) * 100)
}]

是否可以使用聚合/项目/组?
我就是这么想的:
AnalyticsModel.aggregate([
      {
        "$project" : {
          users: {$size: "$loginTrack"},
          "createdAt" : 1,
          "_id": 0
        }},
      {
        "$group": {
          "_id": "$createdAt",
          "count": { "$sum": 1 }
        }
      }

输出如下:
[{"_id":"2018-03-22","count":3},{"_id":"2018-03-21","count":2}]

谢谢

最佳答案

可能刚开始只是创建一个发生映射:

 User.find({}, function(err, users) {
  const occurences = {};

  for(const {createdAt} of users){
     occurences[createdAt] = (occurences[createdAt] || 0) +1;
  }

然后,可以在日期之后对数据进行排序并生成结果:
  const timeline = Object.entries(occurences);
  timeline.sort((a,b) => a[0].localeCompare(b[0]));

  const result = [];
  let previous = 0;

  for(const [date, total] of timeline){
    result.push({ date, avg: (total / (total + previous) || 0) * 100 });
    previous = total;
  }

09-25 16:07