1

我需要 mapreduce 来拆分包含 mongodb 中逗号分隔值的字段并计算字段中的值。

4

1 回答 1

1

我创建了如下所示的示例文档。

{ "_id" : ObjectId("5060017f6fd0f104e16540a2"), "field" : "1,2,3,4,5" }
{ "_id" : ObjectId("506001866fd0f104e16540a3"), "field" : "1,2,3" }
{ "_id" : ObjectId("5060018e6fd0f104e16540a4"), "field" : "1,2,3,7,8,9,0,4,3" }
{ "_id" : ObjectId("506001926fd0f104e16540a5"), "field" : "1" }
{ "_id" : ObjectId("506001966fd0f104e16540a6"), "field" : "1,5" }

然后你可以运行下面的 map/reduce 查询来实现你想要的。

map = function() {
    var array = this.field.split(',');
    emit(this.field, array.length);
}

reduce = function(key, values) {
    return values;
}

result = db.runCommand({
        "mapreduce" : "comma", 
        "map" : map,
        "reduce" : reduce,
        "out" : "comma_result"
});

结果是:

> db.comma_result.find();
{ "_id" : "1", "value" : 1 }
{ "_id" : "1,2,3", "value" : 3 }
{ "_id" : "1,2,3,4,5", "value" : 5 }
{ "_id" : "1,2,3,7,8,9,0,4,3", "value" : 9 }
{ "_id" : "1,5", "value" : 2 }
于 2012-09-24T06:49:40.637 回答