Mongodb:每个数组位置的整数集合 [英] Mongodb: aggregate array of integers for each array position

查看:55
本文介绍了Mongodb:每个数组位置的整数集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读Mongodb的有关Aggregation Framework和Mapreduce的文档,但仍然不知道从哪里开始对数组中整数的列"进行聚合. F.i.拥有这些文件:

I am reading Mongodb's docs about Aggregation Framework and Mapreduce, but still have no clue where to begin with aggregating "columns" of integers in array. F.i. having these documents:

[{ "_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为目标?

Is Aggregation Framework enough for this task or should I aim for Mapreduce?

推荐答案

我认为您需要为此进行map reduce,以便编写可以访问数组中特定位置的函数.您可以尝试这样的事情:

I think you'll need map reduce for this, in order to write a function that can access specific positions in the array. You could try something like this:

映射功能:

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函数:

You can then run the following mapReduce function on your collection:

db.foo.mapReduce( M, R, { out : "resultCollection" } )

那应该给您以下预期的结果!

And that should give you the following desired result !

{
"_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]
}

}

这篇关于Mongodb:每个数组位置的整数集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆