javascript - MapReduce 函数 MongoDB NodeJs

标签 javascript node.js mongodb mapreduce

我试图使用mapReduce 函数以数组的形式返回集合中每个对象的字段。这些是我收集的文档。

 { _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 } });

最佳答案

您需要迭代化简器中的值并将结果转换为所需的形式。

示例:在 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;

根据您的示例输入文档,您将获得如下输出:

[ "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();
    }
);

Note: I'm not handling any error so please do defensive coding.

关于javascript - MapReduce 函数 MongoDB NodeJs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40177205/

相关文章:

javascript - 无法使用 Node.js 从 mongoDB 检索数据

javascript - 动态表格宽度

javascript - 多个表单提交失败

javascript - 在 webCaht UI 中重置对话

javascript - undefined offset : 1 after exploding "/"

c# - 如何使用 C# Mongodb 驱动程序类型化方法更新数组文档元素的字段

javascript - JavaScript/Node 中的数据模型定义标准

web-services - 何时使用socket.io?

node.js - 如何对sequelize 查询的每个结果进行API 调用?

java - 如何使用 java 使用 ObjectIds 创建查询?