gpt4 book ai didi

mongodb - 高级数据聚合 : counting average in MongoDB collections

转载 作者:可可西里 更新时间:2023-11-01 09:25:24 29 4
gpt4 key购买 nike

我有一组文档,例如:

{
"browser" : "firefox",
"version" : "4.0.1"
}

{
"browser" : "firefox",
"version" : "3.6.2"
}

{
"browser" : "ie",
"version" : "8.0"
}

如何计算所有浏览器的平均值以便结果为:

global firefox: 66%
global ie: 33%

precise firefox:
4.0.1: 50%
3.6.3: 50%

棘手的部分是我不想在数组中提供所有可用的 Firefox 版本。 MongoDB 查询应该找到集合中的所有不同版本并计算所有版本的平均值。

提前致谢!

最佳答案

这是一个使用纯数字(例如 0.5 而不是 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();
// => { "_id" : "global", "value" : { "firefox" : 0.6666666666666666, "ie" : 0.3333333333333333 } }
// => { "_id" : "local", "value" : { "firefox" : { "4.0.1" : 0.5, "3.6.2" : 0.5 }, "ie" : { "8.0" : 1 } } }

关于mongodb - 高级数据聚合 : counting average in MongoDB collections,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6256918/

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