gpt4 book ai didi

javascript - Mongoose 占总数的百分比

转载 作者:可可西里 更新时间:2023-11-01 10:47:02 25 4
gpt4 key购买 nike

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

型号:

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

我想知道每天唯一新 session 总数的百分比,这意味着计算前一天的 session 数,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;
}

关于javascript - Mongoose 占总数的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49447495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com