Here is a solution that produces your statistics with clean numbers (e.g. 0.5 instead of 50%):
var m = function() {
emit('global', this.browser);
emit('local', [this.browser, this.version]);
};
var r = function(key, values) {
var global={}, local={}, total=0, i, j, x;
if (key == 'global') {
values.forEach(function(v) {
global[v] = (global[v]||0) + 1;
total += 1;
});
for (i in global) { global[i] = global[i] / total; }
return global;
} else if (key == 'local') {
values.forEach(function(v) {
if (!local[v[0]]) { local[v[0]] = {}; }
x = local[v[0]];
x[v[1]] = (x[v[1]]||0) + 1;
});
for (i in local) {
total = 0;
x = local[i];
for (j in x) { total += x[j]; }
for (j in x) { x[j] = x[j] / total; }
}
return local;
};
};
db.browsers.mapReduce(m, r, {out:'bout'});
db.bout.find();
source
share