Aggregation Pipeline Stages聚合管道阶段

In the db.collection.aggregate() method and db.aggregate() method, pipeline stages appear in an array. db.collection.aggregate()方法和db.aggregate()方法中,管道阶段出现在一个数组中。Documents pass through the stages in sequence.文件按顺序经过各个阶段。

Stages阶段

db.collection.aggregate() Stages阶段

All except the $out, $merge, and $geoNear stages can appear multiple times in a pipeline.除了$out$merge$geoNear阶段,其他所有阶段都可以在管道中多次出现。

Note注意

For details on specific operator, including syntax and examples, click on the specific operator to go to its reference page.有关特定运算符的详细信息,包括语法和示例,请单击特定运算符以转到其参考页。

db.collection.aggregate( [ { <stage> }, ... ] )
Stage阶段Description描述
$addFields

Adds new fields to documents. 向文档中添加新字段。Similar to $project, $addFields reshapes each document in the stream; specifically, by adding new fields to output documents that contain both the existing fields from the input documents and the newly added fields.$project类似,$addFields重塑流中的每个文档;具体来说,通过向输出文档添加新字段,这些文档既包含输入文档中的现有字段,也包含新添加的字段。

$set is an alias for $addFields.$addFields的别名。

$bucketCategorizes incoming documents into groups, called buckets, based on a specified expression and bucket boundaries.根据指定的表达式和存储桶边界,将传入文档分类为组,称为存储桶。
$bucketAutoCategorizes incoming documents into a specific number of groups, called buckets, based on a specified expression. 根据指定的表达式将传入文档分类为特定数量的组,称为bucket。Bucket boundaries are automatically determined in an attempt to evenly distribute the documents into the specified number of buckets.将自动确定存储桶边界,以便将文档均匀分布到指定数量的存储桶中。
$collStatsReturns statistics regarding a collection or view.返回有关集合或视图的统计信息。
$count

Returns a count of the number of documents at this stage of the aggregation pipeline.返回聚合管道此阶段的文档数计数。

Distinct from the $count aggregation accumulator.有别于$count聚合累加器。

$densify

Creates new documents in a sequence of documents where certain values in a field are missing.在字段中缺少某些值的文档序列中创建新文档。

$documentsReturns literal documents from input expressions.从输入表达式返回文本文档。
$facetProcesses multiple aggregation pipelines within a single stage on the same set of input documents. 在同一组输入文档的单个阶段中处理多个聚合管道Enables the creation of multi-faceted aggregations capable of characterizing data across multiple dimensions, or facets, in a single stage.支持创建多方面的聚合,能够在单个阶段跨多个维度或方面描述数据。
$fill

Populates null and missing field values within documents.在文档中填充null的和缺少的字段值。

$geoNear

Returns an ordered stream of documents based on the proximity to a geospatial point. 根据与地理空间点的接近程度返回有序的文档流。Incorporates the functionality of $match, $sort, and $limit for geospatial data. The output documents include an additional distance field and can include a location identifier field.合并了地理空间数据的$match$sort$limit功能。输出文档包括一个额外的距离字段,还可以包括一个位置标识符字段。

$graphLookupPerforms a recursive search on a collection. 对集合执行递归搜索。To each output document, adds a new array field that contains the traversal results of the recursive search for that document.在每个输出文档中,添加一个新的数组字段,其中包含该文档递归搜索的遍历结果。
$groupGroups input documents by a specified identifier expression and applies the accumulator expression(s), if specified, to each group. 按指定的标识符表达式对输入文档进行分组,并将累加器表达式(如果指定)应用于每个组。Consumes all input documents and outputs one document per each distinct group. 使用所有输入文档,并为每个不同的组输出一个文档。The output documents only contain the identifier field and, if specified, accumulated fields.输出文档仅包含标识符字段和累加字段(如果指定)。
$indexStatsReturns statistics regarding the use of each index for the collection.返回有关集合中每个索引使用情况的统计信息。
$limitPasses the first n documents unmodified to the pipeline where n is the specified limit. 将前n个未修改的文档传递到管道,其中n是指定的限制。For each input document, outputs either one document (for the first n documents) or zero documents (after the first n documents).对于每个输入文档,输出一个文档(前n个文档)或零个文档(前n个文档之后)。
$listSessionsLists all sessions that have been active long enough to propagate to the system.sessions collection.列出所有活动时间足以传播到system.sessions集合的会话。
$lookupPerforms a left outer join to another collection in the same database to filter in documents from the "joined" collection for processing.对同一数据库中的另一个集合执行左外部联接,以从“联接”集合中筛选文档进行处理。
$matchFilters the document stream to allow only matching documents to pass unmodified into the next pipeline stage. 筛选文档流,只允许匹配的文档未经修改地传递到下一个管道阶段。$match uses standard MongoDB queries. $match使用标准的MongoDB查询。For each input document, outputs either one document (a match) or zero documents (no match).对于每个输入文档,输出一个文档(匹配)或零个文档(不匹配)。
$merge

Writes the resulting documents of the aggregation pipeline to a collection. 将聚合管道的结果文档写入集合。The stage can incorporate (insert new documents, merge documents, replace documents, keep existing documents, fail the operation, process documents with a custom update pipeline) the results into an output collection. 该阶段可以将结果(插入新文档、合并文档、替换文档、保留现有文档、操作失败、使用自定义更新管道处理文档)合并到输出集合中。To use the $merge stage, it must be the last stage in the pipeline.要使用$merge阶段,它必须是管道中的最后一个阶段。

New in version 4.2.在版本4.2中新增

$outWrites the resulting documents of the aggregation pipeline to a collection. 将聚合管道的结果文档写入集合。To use the $out stage, it must be the last stage in the pipeline.要使用$out阶段,它必须是管道中的最后一个阶段。
$planCacheStatsReturns plan cache information for a collection.返回集合的计划缓存信息。
$project

Reshapes each document in the stream, such as by adding new fields or removing existing fields. 重塑流中的每个文档,例如通过添加新字段或删除现有字段。For each input document, outputs one document.对于每个输入文档,输出一个文档。

See also $unset for removing existing fields.有关删除现有字段的信息,请参阅$unset

$redactReshapes each document in the stream by restricting the content for each document based on information stored in the documents themselves. 通过基于文档本身中存储的信息限制每个文档的内容来重塑流中的每个文档。Incorporates the functionality of $project and $match. 包含$project$match的功能。Can be used to implement field level redaction. 可用于实现字段级编校。For each input document, outputs either one or zero documents.对于每个输入文档,输出一个或零个文档。
$replaceRoot

Replaces a document with the specified embedded document. 用指定的嵌入文档替换文档。The operation replaces all existing fields in the input document, including the _id field. 该操作将替换输入文档中的所有现有字段,包括_id字段。Specify a document embedded in the input document to promote the embedded document to the top level.指定嵌入到输入文档中的文档,以将嵌入的文档提升到顶层。

$replaceWith is an alias for $replaceRoot stage.$replaceRoot阶段的别名。

$replaceWith

Replaces a document with the specified embedded document. 用指定的嵌入文档替换文档。The operation replaces all existing fields in the input document, including the _id field. 该操作将替换输入文档中的所有现有字段,包括_id字段。Specify a document embedded in the input document to promote the embedded document to the top level.指定嵌入到输入文档中的文档,以将嵌入的文档提升到顶层。

$replaceWith is an alias for $replaceRoot stage.$replaceRoot阶段的别名。

$sampleRandomly selects the specified number of documents from its input.从输入中随机选择指定数量的文档。
$search

Performs a full-text search of the field or fields in an Atlas collection.Atlas集合中的一个或多个字段执行全文搜索。

Note注意

$search is only available for MongoDB Atlas clusters, and is not available for self-managed deployments. 仅适用于MongoDB Atlas群集,不适用于自我管理的部署。To learn more, see Atlas Search Aggregation Pipeline Stages.要了解更多信息,请参阅Atlas搜索聚合管道阶段

$searchMeta

Returns different types of metadata result documents for the Atlas Search query against an Atlas collection.针对Atlas集合返回Atlas搜索查询的不同类型元数据结果文档。

Note注意

$searchMeta is only available for MongoDB Atlas clusters running MongoDB v4.4.9 or higher, and is not available for self-managed deployments. 仅适用于运行MongoDB v4.4.9或更高版本的MongoDB Atlas群集,不适用于自我管理的部署。To learn more, see Atlas Search Aggregation Pipeline Stages.要了解更多信息,请参阅Atlas搜索聚合管道阶段

$set

Adds new fields to documents. 向文档中添加新字段。Similar to $project, $set reshapes each document in the stream; specifically, by adding new fields to output documents that contain both the existing fields from the input documents and the newly added fields.$project类似,$set重塑流中的每个文档;具体来说,通过向输出文档添加新字段,这些文档既包含输入文档中的现有字段,也包含新添加的字段。

$set is an alias for $addFields stage.$addFields阶段的别名。

$setWindowFields

Groups documents into windows and applies one or more operators to the documents in each window.将文档分组到窗口中,并对每个窗口中的文档应用一个或多个运算符。

New in version 5.0.在版本5.0中新增

$skipSkips the first n documents where n is the specified skip number and passes the remaining documents unmodified to the pipeline. 跳过前n个文档,其中n是指定的跳过编号,并将未修改的剩余文档传递到管道。For each input document, outputs either zero documents (for the first n documents) or one document (if after the first n documents).对于每个输入文档,输出零个文档(对于前n个文档)或一个文档(如果在前n个文档之后)。
$sortReorders the document stream by a specified sort key. Only the order changes; the documents remain unmodified. For each input document, outputs one document.按指定的排序键对文档流重新排序。只有顺序改变;这些文件没有修改。对于每个输入文档,输出一个文档。
$sortByCountGroups incoming documents based on the value of a specified expression, then computes the count of documents in each distinct group.根据指定表达式的值对传入文档进行分组,然后计算每个不同组中的文档数。
$unionWith

Performs a union of two collections; i.e. combines pipeline results from two collections into a single result set.执行两个集合的并集;将两个集合的管道结果合并到一个结果集中。

New in version 4.4.在版本4.4中新增

$unset

Removes/excludes fields from documents.从文档中删除/排除字段。

$unset is an alias for $project stage that removes fields.是删除字段的$project阶段的别名。

$unwindDeconstructs an array field from the input documents to output a document for each element. 从输入文档中解构数组字段,以输出每个元素的文档。Each output document replaces the array with an element value. 每个输出文档用一个元素值替换数组。For each input document, outputs n documents where n is the number of array elements and can be zero for an empty array.对于每个输入文档,输出n个文档,其中n是数组元素的数量,对于空数组,n可以为零。

For aggregation expression operators to use in the pipeline stages, see Aggregation Pipeline Operators.有关在管道阶段中使用的聚合表达式运算符,请参阅聚合管道运算符

db.aggregate() Stages阶段

Starting in version 3.6, MongoDB also provides the db.aggregate() method:从3.6版开始,MongoDB还提供了db.aggregate()方法:

db.aggregate( [ { <stage> }, ... ] )

The following stages use the db.aggregate() method and not the db.collection.aggregate() method.以下阶段使用db.aggregate()方法,而不是db.collection.aggregate()方法。

StageDescription描述
$currentOpReturns information on active and/or dormant operations for the MongoDB deployment.返回有关MongoDB部署的活动和/或休眠操作的信息。
$listLocalSessionsLists all active sessions recently in use on the currently connected mongos or mongod instance. 列出当前连接的mongosmongod实例上最近使用的所有活动会话。These sessions may have not yet propagated to the system.sessions collection.这些会话可能尚未传播到system.sessions集合。

Stages Available for Updates可用于更新的阶段

Starting in MongoDB 4.2, you can use the aggregation pipeline for updates in:从MongoDB 4.2开始,您可以在以下位置使用聚合管道进行更新:

Command命令mongosh Methods方法
findAndModify
update

For the updates, the pipeline can consist of the following stages:对于更新,管道可包括以下阶段:

Alphabetical Listing of Stages按字母顺序排列的阶段清单

Name名称Description描述
$addFieldsAdds new fields to documents. Outputs documents that contain all existing fields from the input documents and newly added fields.向文档中添加新字段。输出包含输入文档和新添加字段中所有现有字段的文档。
$bucketCategorizes incoming documents into groups, called buckets, based on a specified expression and bucket boundaries.根据指定的表达式和存储桶边界,将传入文档分类为组,称为存储桶。
$bucketAutoCategorizes incoming documents into a specific number of groups, called buckets, based on a specified expression. 根据指定的表达式将传入文档分类为特定数量的组,称为bucket。Bucket boundaries are automatically determined in an attempt to evenly distribute the documents into the specified number of buckets.将自动确定存储桶边界,以便将文档均匀分布到指定数量的存储桶中。
$collStatsReturns statistics regarding a collection or view.返回有关集合或视图的统计信息。
$count

Returns a count of the number of documents at this stage of the aggregation pipeline.返回聚合管道此阶段的文档数计数。

Distinct from the $count aggregation accumulator.有别于$count聚合累加器。

$currentOpReturns information on active and/or dormant operations for the MongoDB deployment. 返回有关MongoDB部署的活动和/或休眠操作的信息。To run, use the db.aggregate() method.要运行,请使用db.aggregate()方法。
$densify

Creates new documents in a sequence of documents where certain values in a field are missing.在字段中缺少某些值的文档序列中创建新文档。

$facetProcesses multiple aggregation pipelines within a single stage on the same set of input documents. 在同一组输入文档的单个阶段中处理多个聚合管道Enables the creation of multi-faceted aggregations capable of characterizing data across multiple dimensions, or facets, in a single stage.支持创建多方面的聚合,能够在单个阶段跨多个维度或方面描述数据。
$fill

Populates null and missing field values within documents.在文档中填充null的和缺少的字段值。

$geoNear

Returns an ordered stream of documents based on the proximity to a geospatial point. 根据与地理空间点的接近程度返回有序的文档流。Incorporates the functionality of $match, $sort, and $limit for geospatial data. 合并了地理空间数据的$match$sort$limit功能。The output documents include an additional distance field and can include a location identifier field.输出文档包括一个额外的距离字段,还可以包括一个位置标识符字段。

$graphLookupPerforms a recursive search on a collection. 对集合执行递归搜索。To each output document, adds a new array field that contains the traversal results of the recursive search for that document.在每个输出文档中,添加一个新的数组字段,其中包含该文档递归搜索的遍历结果。
$groupGroups input documents by a specified identifier expression and applies the accumulator expression(s), if specified, to each group. 按指定的标识符表达式对输入文档进行分组,并将累加器表达式(如果指定)应用于每个组。Consumes all input documents and outputs one document per each distinct group. 使用所有输入文档,并为每个不同的组输出一个文档。The output documents only contain the identifier field and, if specified, accumulated fields.输出文档仅包含标识符字段和累加字段(如果指定)。
$indexStatsReturns statistics regarding the use of each index for the collection.返回有关集合中每个索引使用情况的统计信息。
$limitPasses the first n documents unmodified to the pipeline where n is the specified limit. 将前n个未修改的文档传递到管道,其中n是指定的限制。For each input document, outputs either one document (for the first n documents) or zero documents (after the first n documents).对于每个输入文档,输出一个文档(前n个文档)或零个文档(前n个文档之后)。
$listLocalSessionsLists all active sessions recently in use on the currently connected mongos or mongod instance. 列出当前连接的mongosmongod实例上最近使用的所有活动会话。These sessions may have not yet propagated to the system.sessions collection.这些会话可能尚未传播到system.sessions集合。
$listSessionsLists all sessions that have been active long enough to propagate to the system.sessions collection.列出所有活动时间足以传播到system.sessions集合的会话。
$lookupPerforms a left outer join to another collection in the samedatabase to filter in documents from the "joined" collection for processing.“连接到”选项卡中的“连接到另一个集合的外部文档”执行“从集合到左侧的连接到”处理。
$matchFilters the document stream to allow only matching documents to pass unmodified into the next pipeline stage. 筛选文档流,只允许匹配的文档未经修改地传递到下一个管道阶段。$match uses standard MongoDB queries. 使用标准MongoDB查询。For each input document, outputs either one document (a match) or zero documents (no match).对于每个输入文档,输出一个文档(匹配)或零个文档(不匹配)。
$merge

Writes the resulting documents of the aggregation pipeline to a collection. 将聚合管道的结果文档写入集合。The stage can incorporate (insert new documents, merge documents, replace documents, keep existing documents, fail the operation, process documents with a custom update pipeline) the results into an output collection. 该阶段可以将结果(插入新文档、合并文档、替换文档、保留现有文档、操作失败、使用自定义更新管道处理文档)合并到输出集合中。To use the $merge stage, it must be the last stage in the pipeline.要使用$merge阶段,它必须是管道中的最后一个阶段。

New in version 4.2.在版本4.2中新增

$outWrites the resulting documents of the aggregation pipeline to a collection. 将聚合管道的结果文档写入集合。To use the $out stage, it must be the last stage in the pipeline.要使用$out阶段,它必须是管道中的最后一个阶段。
$planCacheStatsReturns plan cache information for a collection.返回集合的计划缓存信息。
$projectReshapes each document in the stream, such as by adding new fields or removing existing fields. 重塑流中的每个文档,例如通过添加新字段或删除现有字段。For each input document, outputs one document.对于每个输入文档,输出一个文档。
$redactReshapes each document in the stream by restricting the content for each document based on information stored in the documents themselves. 通过基于文档本身中存储的信息限制每个文档的内容来重塑流中的每个文档。Incorporates the functionality of $project and $match. 包含$project$match的功能。Can be used to implement field level redaction. 可用于实现字段级编校。For each input document, outputs either one or zero documents.对于每个输入文档,输出一个或零个文档。
$replaceRootReplaces a document with the specified embedded document. 用指定的嵌入文档替换文档。The operation replaces all existing fields in the input document, including the _id field. 该操作将替换输入文档中的所有现有字段,包括_id字段。Specify a document embedded in the input document to promote the embedded document to the top level.指定嵌入到输入文档中的文档,以将嵌入的文档提升到顶层。
$replaceWith

Replaces a document with the specified embedded document. 用指定的嵌入文档替换文档。The operation replaces all existing fields in the input document, including the _id field. 该操作将替换输入文档中的所有现有字段,包括_id字段。Specify a document embedded in the input document to promote the embedded document to the top level.指定嵌入到输入文档中的文档,以将嵌入的文档提升到顶层。

Alias for $replaceRoot.$replaceRoot的别名。

$sampleRandomly selects the specified number of documents from its input.从输入中随机选择指定数量的文档。
$search

Performs a full-text search of the field or fields in an Atlas collection.对Atlas集合中的一个或多个字段执行全文搜索。

Note注意

$search is only available for MongoDB Atlas clusters, and is not available for self-managed deployments.仅适用于MongoDB Atlas群集,不适用于自我管理的部署。

To learn more, see Atlas Search Aggregation Pipeline Stages.要了解更多信息,请参阅Atlas搜索聚合管道阶段

$searchMeta

Returns different types of metadata result documents for the Atlas Search query against an Atlas collection.针对Atlas集合返回Atlas搜索查询的不同类型元数据结果文档。

Note注意

$searchMeta is only available for MongoDB Atlas clusters running MongoDB v4.4.9 or higher, and is not available for self-managed deployments.仅适用于运行MongoDB v4.4.9或更高版本的MongoDB Atlas群集,不适用于自我管理的部署。

To learn more, see Atlas Search Aggregation Pipeline Stages.要了解更多信息,请参阅Atlas搜索聚合管道阶段

$set

Adds new fields to documents. Outputs documents that contain all existing fields from the input documents and newly added fields.向文档中添加新字段。输出包含输入文档和新添加字段中所有现有字段的文档。

Alias for $addFields.$addFields的别名。

$setWindowFields

Groups documents into windows and applies one or more operators to the documents in each window.将文档分组到窗口中,并对每个窗口中的文档应用一个或多个运算符。

New in version 5.0.在版本5.0中新增

$skipSkips the first n documents where n is the specified skip number and passes the remaining documents unmodified to the pipeline. 跳过前n个文档,其中n是指定的跳过编号,并将未修改的剩余文档传递到管道。For each input document, outputs either zero documents (for the first ndocuments) or one document (if after the first n documents).对于每个输入文档,输出零个文档(对于前n个文档)或一个文档(如果在前n个文档之后)。
$sortReorders the document stream by a specified sort key. 按指定的排序键对文档流重新排序。Only the order changes; the documents remain unmodified. For each input document, outputs one document.只有顺序改变;这些文件没有修改。对于每个输入文档,输出一个文档。
$sortByCountGroups incoming documents based on the value of a specified expression, then computes the count of documents in each distinct group.根据指定表达式的值对传入文档进行分组,然后计算每个不同组中的文档数。
$unionWith

Performs a union of two collections; i.e. combines pipeline results from two collections into a single result set.执行两个集合的并集;将两个集合的管道结果合并到一个结果集中。

New in version 4.4.在版本4.4中新增

$unset

Removes/exludes fields from documents.从文档中删除/排除字段。

Alias for $project stage that excludes/removes fields.用于排除/删除字段的$project阶段的别名。

$unwindDeconstructs an array field from the input documents to output a document for each element. 从输入文档中解构数组字段,以输出每个元素的文档。Each output document replaces the array with an element value. 每个输出文档用一个元素值替换数组。For each input document, outputs n documents where n is the number of array elements and can be zero for an empty array.对于每个输入文档,输出n个文档,其中n是数组元素的数量,对于空数组,n可以为零。
←  $bit$addFields (aggregation) →