在javascript/node.js中重现MongoDB的地图/发射功能(没有MongoDB) [英] Reproducing MongoDB's map/emit functionality in javascript/node.js (without MongoDB)

查看:58
本文介绍了在javascript/node.js中重现MongoDB的地图/发射功能(没有MongoDB)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢MongoDB提供的用于执行映射/归约任务的功能,特别是mapper函数中的emit().没有MongoDB的情况下,如何在javascript/node.js中重现下面显示的地图行为?

I like the functionality that MongoDB provides for doing map/reduce tasks, specifically the emit() in the mapper function. How can I reproduce the map behavior shown below in javascript/node.js without MongoDB?

[{ cust_id: "A123", amount: 500 }, { cust_id: "A123", amount: 250 }, { cust_id: "B212", amount: 200 }] 

映射到-

[{ "A123": [500, 200] }, { "B212": 200 }]

一个使它像Mongo的一行上的throw()一样简单的库将是不错的选择,但是本机函数也可以完成该工作.

A library that makes it as simple as Mongo's one line emit() would be nice but native functions would do the job as well.

推荐答案

如果您只想使用emit语法,则有可能.扫描出函数体并传递新的发射函数.

If you just neeed to have the emit syntax, it's possible. Scan out the function body and pass in a new emit function.

function mapReduce(docs, m, r) {
  var groups = {}
  function emit(key, value) {
    if (!groups[key]) { groups[key] = [] }
    groups[key].push(value)
  }
  var fn = m.toString()
  var body = fn.substring(fn.indexOf('{') + 1, fn.lastIndexOf('}'))
  var map = new Function('emit', body)
  docs.forEach(function (doc) {
    map.call(doc, emit)
  })
  var outs = []
  Object.keys(groups).forEach(function (key) {
    outs.push({ _id: key, value: r(key, groups[key]) })
  })
  return outs
}

编辑,忘记示例:

var docs = // from above

Array.sum = function (values) {
  return values.reduce(function (a, b) { return a + b })
}

mapReduce(docs, 
  function () {
    emit(this.cust_id, this.amount)
  },
  function (k, values) {
    return Array.sum(values)
  }
)

// [ { _id: 'A123', value: 750 }, { _id: 'B212', value: 200 } ]

这篇关于在javascript/node.js中重现MongoDB的地图/发射功能(没有MongoDB)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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