【问题标题】:Mongoose percentage of total猫鼬占总数的百分比
【发布时间】:2018-09-02 00:03:52
【问题描述】:

我有一个看起来像这样的模型:

型号:

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

谢谢

【问题讨论】:

  • 到目前为止你绑了什么?
  • 我编辑了问题:)

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


【解决方案1】:

也许一开始只是创建一个发生图:

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

【讨论】:

  • 谢谢,但你能在 1 个请求中做到吗?
  • 只有一个请求?
  • 是的,当然,我的意思是使用 mongo 的聚合工具
猜你喜欢
  • 2020-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多