我正在阅读Mongodb关于聚合框架和Mapreduce的文档,但仍然不知道从哪里开始聚合数组中的整数“列”。 F.i.有这些文件:
[{ "_id" : "A", "agent" : "006", "score" : [ 1, 0, 0 ], "qv" : [ 1, 0, 1, 0, 1 ] },
{ "_id" : "B", "agent" : "006", "score" : [ 0, 1, 0 ], "qv" : [ 1, 0, 1, 0, 1 ] },
{ "_id" : "C", "agent" : "006", "score" : [ 1, 0, 0 ], "qv" : [ 1, 0, 1, 0, 0 ] },
{ "_id" : "D", "agent" : "007", "score" : [ 1, 0, 0 ], "qv" : [ 1, 0, 1, 0, 0 ] }]
预期结果应该是:
[
{"agent": "006", "score": [2, 1, 0], "qv": [3, 0, 3, 0, 2]},
{"agent": "007", "score": [1, 0, 0], "qv": [1, 0, 1, 0, 0]}
]
聚合框架是否足以完成此任务,还是应该针对Mapreduce?
答案 0 :(得分:3)
我认为你需要map reduce,以便编写一个可以访问数组中特定位置的函数。你可以尝试这样的事情:
映射功能:
var M = function() {
emit( this.agent, { score : this.score, qv : this.qv } )
}
减少功能:
var R = function(key, values) {
var result = { score : [0, 0, 0], qv : [0, 0, 0, 0, 0] };
values.forEach( function(value) {
for ( var i = 0; i < value.score.length; i ++ ) {
result.score[i] += parseInt(value.score[i]);
}
for ( var i = 0; i < value.qv.length; i ++ ) {
result.qv[i] += parseInt(value.qv[i]);
}
});
return result;
}
然后,您可以在集合上运行以下mapReduce函数:
db.foo.mapReduce( M, R, { out : "resultCollection" } )
这应该会给你以下期望的结果!
{
"_id" : "006",
"value" : {
"score" : [2, 1, 0],
"qv" : [ 3, 0, 3, 0, 2 ]
}
}
{
"_id" : "007",
"value" : {
"score" : [ 1, 0, 0],
"qv" : [ 1, 0, 1, 0, 0]
}
}