Uploaded image for project: 'Core Server'
  1. Core Server
  2. SERVER-34281

ES6 arrow functions (lambdas) do not work with map-reduce

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Open
    • Priority: Major - P3
    • Resolution: Unresolved
    • Affects Version/s: None
    • Fix Version/s: Backlog
    • Component/s: JavaScript, MapReduce
    • Labels:
      None
    • Operating System:
      ALL
    • Steps To Reproduce:
      Hide

      var db = db.getSiblingDB('test');
      db.lamdba_strangeness.insertMany([{a:1}, {a:2}, {a:3}]);
       
      var mapFunction = function() { emit(this.ns, Object.bsonsize(this)); };
      var mapLamdba = () => { emit(this.ns, Object.bsonsize(this)) };
       
      var reduce = function(key, values) {
        return Array.sum(values);
      };
       
      var options = {
        out: {inline:1}
      };
       
      print("Using function() {}:");
      printjson(db.lamdba_strangeness.mapReduce(mapFunction, reduce, options).results);
      print("Using () => {}:");
      printjson(db.lamdba_strangeness.mapReduce(mapLamdba, reduce, options).results);
       
      db.lamdba_strangeness.drop();
      

      Results:

      $ mongo lamdba_strangeness.js
      MongoDB shell version v3.6.3
      connecting to: mongodb://127.0.0.1:27017
      MongoDB server version: 3.6.3
      Using function() {}:
      [ { "_id" : null, "value" : 99 } ]
      Using () => {}:
      [ ]
      

      Show
      var db = db.getSiblingDB('test'); db.lamdba_strangeness.insertMany([{a:1}, {a:2}, {a:3}]);   var mapFunction = function() { emit(this.ns, Object.bsonsize(this)); }; var mapLamdba = () => { emit(this.ns, Object.bsonsize(this)) };   var reduce = function(key, values) { return Array.sum(values); };   var options = { out: {inline:1} };   print("Using function() {}:"); printjson(db.lamdba_strangeness.mapReduce(mapFunction, reduce, options).results); print("Using () => {}:"); printjson(db.lamdba_strangeness.mapReduce(mapLamdba, reduce, options).results);   db.lamdba_strangeness.drop(); Results: $ mongo lamdba_strangeness.js MongoDB shell version v3.6.3 connecting to: mongodb://127.0.0.1:27017 MongoDB server version: 3.6.3 Using function() {}: [ { "_id" : null, "value" : 99 } ] Using () => {}: [ ]

      Description

      Because ES6 arrow functions (aka lambdas) do not bind this (see Arrow functions), they do not work with the map-reduce framework in MongoDB.

      For many people, lamdbas are seen as a more concise syntax and do not realize they behave differently. Either we should improve map-reduce to support ES6 arrow functions or clearly document that they are not supported (and why) in the map portion of map-reduce.

        Attachments

          Activity

            People

            • Votes:
              0 Vote for this issue
              Watchers:
              10 Start watching this issue

              Dates

              • Created:
                Updated: