翻译或纠错本页面

映射化简

映射化简是一种将大量数据转换为有价值的*聚合*结果的数据处理方式。在MongoDB中,使用 mapReduce 命令来执行映射化简的操作。

请看下面的映射化简操作:

Diagram of the annotated map-reduce operation.

在这个映射化简操作中,MongoDB对每个输入文档(例如集合中满足查询条件的文档)执行了*map*操作。映射操作输出了键值对结果。对那些有多个值的关键字,MongoDB执行*reduce*操作,收集并压缩了最终的聚合结果。然后MongoDB把结果保存到一个集合中。化简函数还可以把结果输出到*finalize*函数,进一步对聚合结果做处理,当然这步是可选的。

在MongoDB中,所有的映射化简函数都是使用JavaScript编写,并且运行在 mongod 进程中。映射化简操作使用一个集合中文档作为*输入*,并且可以在映射阶段之前执行任意的排序和限定操作。 mapReduce 命令可以把结果作为一个文档来返回,也可以把结果写入集合。输入集合和输出集合可以是分片的。

注解

对于大部分的聚合操作, 聚合管道 有着更好的性能和更加一致的接口。当然,映射化简操作比聚合管道的灵活性要好一些。

映射化简的JavaScript方法

In MongoDB, map-reduce operations use custom JavaScript functions to map, or associate, values to a key. If a key has multiple values mapped to it, the operation reduces the values for the key to a single object.

映射化简使用JavaScript函数来实现,有着很高的灵活性。例如,当处理一个文档的时候,映射函数可以映射多个键值对或者一个也不映射。映射化简还可以在结束的时候使用JavaScript对聚合结果做最后的修改,例如附加的计算。

映射化简的特点

In MongoDB, the map-reduce operation can write results to a collection or return the results inline. If you write map-reduce output to a collection, you can perform subsequent map-reduce operations on the same input collection that merge replace, merge, or reduce new results with previous results. See mapReduce and 对增量数据做Map-Reduce for details and examples.

如果选择映射化简操作即时返回结果,这些文档一定要在 BSON文档大小 限制以内,当前这个限制是16MB。关于映射化简操作的限制信息可以参考 mapReduce 文档。

MongoDB supports map-reduce operations on sharded collections. Map-reduce operations can also output the results to a sharded collection. See Map-Reduce和分片集合.

Views do not support map-reduce operations.