如何在MapReduce中使用变量?

时间:2015-07-20 09:30:09

标签: javascript mongodb mapreduce

我在MapReduce中有以下脚本:

splitAndGroupServices = function(members) {
    var mapFn = function() {
       for(var j in this.services) {
         var service = this.services[j];
         if(service.member_id in members)
             emit(service.member_id, service);
       }
     }

     var reduceFn = ...; 
     var finalizeFn = ...;
     db.items.mapReduce(mapFn, reduceFn, {out: {inline:1}, finalize: finalizeFn});
}

我打电话的时候:

db.loadServerScripts();
splitAndGroupServices({b1: 0, b2: 1});

我一直收到错误:

"errmsg" : "exception: ReferenceError: members is not defined near 'ber_id in members) {             emit(ser'  (line 4)",

如何将外部函数变量传递给内部函数变量?在JS中它实际上是可能的,但Mongo不喜欢它。

1 个答案:

答案 0 :(得分:1)

mapReduce命令支持在mapperreducerfinalize阶段共享的“范围”:

db.items.mapReduce(
    mapFn,
    reduceFn, 
   { 
       "scope": { "members": members },
       "out": { "inline": 1 },
       "finalize": finalizeFn
   }
)

这被视为该过程的“全局”,任何修改都会进入下一阶段或在该阶段同样可用。它是“传递变量”的标准方法,可用于任何舞台功能。