在javascript中打印直方图?

时间:2019-06-16 11:20:10

标签: javascript mongo-shell

我有一个查询,它检查我的mongo集合文档的kb大小,如下所示:

db.myCollection.find().forEach(function(obj)
{
  var size = Object.bsonsize(obj)
  print('document id: ' + obj._id + ' size: ' + size/1024)
});

它会打印:

document id: 57b6e0561a7b8900011bafhr size: 463.248046875

但是我想打印一个如下的直方图:

bigger than 100kb -> 1,000,000 docs
bigget than 200kb -> 500,000 docs
bigger than 300kb -> 300,000 docs 
...

max doc 750kb

如何在javascript中做到这一点?

1 个答案:

答案 0 :(得分:0)

您可以尝试简单的操作,例如:

// an array of 100 random numbers 0-100
var arr = []; 
for(var i=0;i<100;i++) 
   arr.push(Math.random()*100)

// reducing the array to "histogram"
// does not create empty bins
arr.reduce(function(acc,cur){ 
   var k = Math.floor(cur/10)*10; // creates bins of 0-9, 10-19, 20-29,..., 90-99
   if (!(k in acc)) acc[k]=0;     // creates a bin if neccessary
   acc[k]++;                      // increments the bin
   return acc;
},[]);

输出(键表示bin,值是元素计数):

0: 10
10: 12
20: 4
30: 8
40: 8
50: 10
60: 12
70: 12
80: 10
90: 14