计算 0 到 100 的百分位数(步骤 5)
// { "session": 1, "date" : 2013-08-27 11:00::00, "latency" : 403 }
// { "session": 1, "date" : 2013-08-27 11:00::01, "latency" : 1022 }
// { "session": 1, "date" : 2013-08-27 11:00::02, "latency" : 455 }
// { "session": 1, "date" : 2013-08-27 11:00::02, "latency" : 307 }
// { "session": 2, "date" : 2013-08-27 12:00::00, "latency" : 403 }
// { "session": 2, "date" : 2013-08-27 12:00::01, "latency" : 1022 }
// { "session": 2, "date" : 2013-08-27 12:00::02, "latency" : 455 }
// { "session": 2, "date" : 2013-08-27 12:00::02, "latency" : 307 }
var interval = 5
db.getCollection.aggregate([
{
$group:{
_id: { $toString: "$session" },
value: { $push: "$atency" }
}
},
{
$addFields:{
index : {$range: [0, 100, interval]}
}
},
{$unwind: "$index"},
{
$addFields:{
p_index : {$divide: ["$index", 100]}
}
},
{
$addFields:{
percentile_x : {$toDouble: {'$arrayElemAt': ['$value', {'$floor': {'$multiply': ["$p_index", {'$size': '$value'}]}}]}}
}
},
{ $project: {
'percentile': "$index",
'value': "$percentile_x"
}
},
{$sort: {
percentile: 1
}
}
])