[英]MapReduce function MongoDB NodeJs
I am trying to return a field of every object in my collection in form of array using mapReduce function. 我试图使用mapReduce函数以数组的形式返回集合中每个对象的字段。 These are my documents in a collection.
这些是我收藏的文件。
{ _id: '1', name: 'a' },
{ _id: '2', name: 'b' },
{ _id: '4', name: 'c' },
{ _id: '5', name: 'd' },
{ _id: '6', name: 'e' },
{ _id: '7', name: 'f' }
Now i want result in this form ['a','b','c','d','e','f'] . 现在我想要以这种形式[[a','b','c','d','e','f']的结果 。 How i can achieve it, i tried mapReduce but couldn't get the result in this way.
我如何实现它,我尝试了mapReduce,但无法以这种方式获得结果。
This is my code 这是我的代码
collection.mapReduce( function EachBranch( ) {
emit( this.name, this.value);
}, function ( key, values ) {
},{ out: { inline: 1 } });
You'll need to iterate over values in reducer and transform result in desired form. 您需要遍历化简器中的值并以所需的形式转换结果。
Example: Try in mongo shell 示例:在mongo shell中尝试
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;
Based on your sample input documents, you'll get output as: 根据样本输入文档,您将获得以下输出:
[ "a", "b", "c", "d", "e", "f" ]
Update : Node.js solution: 更新 :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();
}
);
Note: I'm not handling any error so please do defensive coding.
注意:我没有处理任何错误,因此请进行防御性编码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.