Reputation: 4823
The map-reduce usage is following
db.myCollection.mapReduce(function() {
emit(this.smth);
},
function(key, values) {
// return something done with key and values
});
My question is, why is the map part implemented to have implicit this
that references the current document being processed? IMO, it would be cleaner to have the current document passed in as an argument to the map function (I prefer to write all my JavaScript without this
).
In practice this also rules out the use of arrow functions in mongo scripts, since this reference does not work with them.
Upvotes: 0
Views: 54
Reputation: 65303
why is the map part implemented to have implicit
this
that references the current document being processed?
MongoDB's Map/Reduce API was created in 2009, which is well before arrow functions were available in JavaScript (via ES6/ES2015). I can only speculate on the design intention, but much has changed in JavaScript (and MongoDB) since the original Map/Reduce implementation.
The this
keyword in a JavaScript method refers to the owner or execution context, so setting it to the current document being processed was perhaps a reasonable convention (or convenience) for JavaScript usage at the time. The reduce
function has a required prototype of function (key, values)
so a map
prototype of function (doc)
might have been more consistent. However, once an API choice is made, any significant breaking changes become more challenging to introduce.
A more modern take on aggregation might look quite different, and this is the general path that MongoDB has taken. The Aggregation Framework introduced in MongoDB 2.2 (August, 2012) is a higher performance approach to data aggregation and should be preferred (where possible) over Map/Reduce.
Successive releases of the MongoDB server have made significant improvements to the features and performance of the Aggregation Framework, while Map/Reduce has not notably evolved. For example, the Aggregation Framework is written in C++ and able to manipulate MongoDB's native BSON data types; Map/Reduce spawns JavaScript threads and has to marshal data between BSON and JavaScript.
In practice this also rules out the use of arrow functions in mongo scripts, since this reference does not work with them.
Indeed. As at MongoDB 4.0, arrow functions are not supported in Map/Reduce. There is a feature request to support arrow functions which can you watch/upvote in the MongoDB issue tracker: SERVER-34281.
Upvotes: 2