2016-10-21 154 views
0

我想使用mapReduce函数以数组的形式返回我的集合中每个对象的字段。这些是我收藏的文件。MapReduce函数MongoDB NodeJs

{ _id: '1', name: 'a' }, 
{ _id: '2', name: 'b' }, 
{ _id: '4', name: 'c' }, 
{ _id: '5', name: 'd' }, 
{ _id: '6', name: 'e' }, 
{ _id: '7', name: 'f' } 

现在我想导致这种形式[ 'A', 'B', 'C', 'd', 'E', 'F']。我如何实现它,我尝试过mapReduce,但无法以这种方式获得结果。

这是我的代码

collection.mapReduce(function EachBranch() { 
     emit(this.name, this.value); 
     }, function (key, values) { 
     },{ out: { inline: 1 } }); 

回答

1

你需要值遍历在减速和期望形式变换结果。

实例:尝试在蒙戈外壳

db.collection.mapReduce(
    function() { 
    emit(1, this.name) 
    }, 
    function(k,v){ 
    var result = {}; 
    result.names = v; 
    return result; 
    }, 
    {out: {inline:1}} 
).results[0].value.names; 

根据您的样品输入文档,你会得到输出:

[ "a", "b", "c", "d", "e", "f" ] 

更新:Node.js的解决方案:

collection.mapReduce(
    function() { 
     emit(1, this.name) 
    }, 
    function (k, v) { 
     var result = {}; 
     result.names = v; 
     return result; 
    }, 
    { out: { inline: 1 } }, 
    function (err, result) { 
     assert.equal(null, err); 

     if (result) { 
      console.log(result[0].value.names); 
     } 
     db.close(); 
    } 
); 

注:我没有处理任何错误,所以请做防御性编码。

+0

我得到“无法读取属性'0'的未定义” –

+0

请参阅上面的** ** NOTE **。我明确提到我没有做任何错误检查。如果没有结果,你会得到错误。我正在离开错误处理。请注意,SO不是一个编码服务。我们在这里帮助但不解决任务或工作。 – Saleem

+0

我明白了,问题出在您的代码中,结果是undefined –