• MongoDB聚合管道(Aggregation Pipeline)


    参考聚合管道简介

    聚合管道

    聚合管道是基于数据处理管道模型的数据聚合框架。文档进入一个拥有多阶段(multi-stage)的管道,并被管道转换成一个聚合结果。最基本的管道阶段提供了跟查询操作类似的过滤和文档转换。其他管道操作提供了根据特殊字段对文档的分组和排序,以及对数组的聚合,包括文档数组。另外,管道阶段可以使用操作符来完成某些任务如计算平均值或者连接字符串。管道阶段可以在管道中出现多次。

    如图所示,

    Diagram of the annotated aggregation pipeline operation. The aggregation pipeline has two stages: ``$match`` and ``$group``.

    聚合管道提供了一种map-reduce的替代方案,并且在map-reduce的复杂性无法保证的情况下,聚合管道可能是一个较好的解决方法。

    聚合管道在值类型和结果大小上有一些限制,详细请参考聚合管道限制

    Map-Reduce

    MongoDB也提供了map-reduce操作来进行聚合。总的来说,map-reduce操作有两个阶段(phase):map阶段处理每个文档并对每个文档产生一个或多个对象,而reduce阶段则合并map操作的结果。当然,map-reduce也可以有一个最终(finalize)阶段来对结果作一个最终修改,这是可选的。跟其他聚合操作类似,map-reduce可以指定查询条件来对输入文档进行选择,或者对输入文档排序和限制输出文档数量。

    Map-reduce使用自定义的JavaScript函数来实现map和reduce操作,以及可选的finalize操作。与聚合管道相比,自定义JavaScript提供了很大的灵活性,所以map-reduce比聚合管道更加灵活,但没有后者效率高。

    Diagram of the annotated map-reduce operation.

    单一目的聚合操作

    对一系列的常用单一目的聚合操作,MongoDB提供了用于专用目的的数据库命令。这些常用的聚合操作是:返回匹配的文档数量,返回某一字段的不相同的值,以及基于某个字段值的分组。所有这些操作从单一集合中聚合文档。这些操作可以实现常见聚合过程,但是它们缺乏灵活性,也不像聚合管道和map-reduce那样可以容纳很多操作阶段。

    Diagram of the annotated distinct operation.

    其他特征和行为

    聚合管道和map-reduce都是在分片集合(sharded collection)上操作。Map-reduce操作也可以输入到一个分片集合中。参见聚合管道和分片集合Map-Reduce和分片集合

    聚合管道在其中的某些阶段可以使用索引提高性能。另外,聚合管道有一个内部优化阶段。详情参见管道符和索引聚合管道优化

    对聚合管道、map-reduce以及特殊分组功能的特性比较,参见聚合命令比较

    管道操作符的种类:

    Name

    Description

    $project

    Reshapes a document stream. $project can rename, add, or remove fields as well as create computed values and sub-documents.

    $match

    Filters the document stream, and only allows matching documents to pass into the next pipeline stage.$match uses standard MongoDB queries.

    $limit

    Restricts the number of documents in an aggregation pipeline.

    $skip

    Skips over a specified number of documents from the pipeline and returns the rest.

    $unwind

    Takes an array of documents and returns them as a stream of documents.

    $group

    Groups documents together for the purpose of calculating aggregate values based on a collection of documents.

    $sort

    Takes all input documents and returns them in a stream of sorted documents.

    $geoNear

    Returns an ordered stream of documents based on proximity to a geospatial point.

  • 相关阅读:
    python 软件目录结构规范 与 模块导入
    Python 序列化之json&pickle模块
    损失函数总结
    从1到n整数中1出现的次数(Java)
    随手编程---快速排序(QuickSort)-Java实现
    从上往下打印二叉树(剑指offer_32.1)
    栈的压入、弹出序列(剑指offer_31)
    63. 搜索旋转排序数组 II(回顾)
    643. 最长绝对文件路径(回顾)
    40. 用栈实现队列
  • 原文地址:https://www.cnblogs.com/sjjsxl/p/5122132.html
Copyright © 2020-2023  润新知