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

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

    • Type: Icon: Bug Bug
    • Resolution: Gone away
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: None
    • Component/s: JavaScript, MapReduce
    • None
    • Query Execution
    • ALL
    • 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 () => {}: [ ]

      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.

            Assignee:
            backlog-query-execution [DO NOT USE] Backlog - Query Execution
            Reporter:
            james.kovacs@mongodb.com James Kovacs
            Votes:
            0 Vote for this issue
            Watchers:
            12 Start watching this issue

              Created:
              Updated:
              Resolved: