为什么 MongoDB map-reduce 隐含了这个

Why does MongoDB map-reduce have implicit this

map-reduce 用法如下

db.myCollection.mapReduce(function() {
  emit(this.smth);
},
function(key, values) {
  // return something done with key and values
});

我的问题是,为什么地图部分实施为具有引用当前正在处理的文档的隐式 this? IMO,将当前文档作为参数传递给 map 函数会更清晰(我更喜欢在没有 this 的情况下编写所有 JavaScript)。

在实践中,这也排除了在 mongo 脚本中使用箭头函数,因为此引用不适用于它们。

why is the map part implemented to have implicit this that references the current document being processed?

MongoDB 的 Map/Reduce API 创建于 2009 年,远早于箭头函数在 JavaScript 中可用(通过 ES6/ES2015)。我只能推测设计意图,但自最初的 Map/Reduce 实施以来 JavaScript(和 MongoDB)发生了很大变化。

JavaScript 方法中的 this 关键字指的是所有者或执行上下文,因此将其设置为正在处理的当前文档可能是 [=42 的合理约定(或方便) =]当时的用法。 reduce function 具有必需的 function (key, values) 原型,因此 function (doc)map 原型可能更一致。但是,一旦做出 API 选择,任何重大的重大更改都将变得更具挑战性。

更现代的聚合方式可能看起来完全不同,这是 MongoDB 所采用的一般路径。 MongoDB 2.2(2012 年 8 月)中引入的 Aggregation Framework 是一种更高性能的数据聚合方法,应该(在可能的情况下)优于 Map/Reduce。

MongoDB 服务器的后续版本对聚合框架的功能和性能进行了重大改进,而 Map/Reduce 并没有显着改进。例如,Aggregation Framework 是用 C++ 编写的,能够操纵 MongoDB 的原生 BSON data types; Map/Reduce 生成 JavaScript 个线程并且必须在 BSON 和 JavaScript 之间编组数据。

In practice this also rules out the use of arrow functions in mongo scripts, since this reference does not work with them.

确实如此。在 MongoDB 4.0 中,Map/Reduce 不支持箭头函数。 MongoDB 问题跟踪器中有支持箭头功能的功能请求,您可以 watch/upvote:SERVER-34281.