猫鼬占总数的百分比

时间:2018-03-23 10:26:31

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

我的模型看起来像这样:

型号:

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}]

由于

1 个答案:

答案 0 :(得分:0)

最初可能只是创建一个出现地图:

 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;
  }