Docs Home / Client Libraries / Node.js / Node.js Driver / Aggregation

Aggregation Pipeline Stages聚合管道阶段

Overview概述

In this guide, you can learn how to create an aggregation pipeline and pipeline stages by using methods in the MongoDB Node.js driver.在本指南中,您可以学习如何使用MongoDB Node.js驱动程序中的方法创建聚合管道和管道阶段。

Build an Aggregation Pipeline构建聚合管道

You can use the Node.js driver to build an aggregation pipeline by creating a pipeline variable or passing aggregation stages directly into the aggregation method. See the following examples to learn more about each of these approaches.您可以使用Node.js驱动程序通过创建管道变量或将聚合阶段直接传递给聚合方法来构建聚合管道。请参阅以下示例以了解有关每种方法的更多信息。

Create a Pipeline创建管道
// Defines the aggregation pipeline定义聚合管道
const pipeline = [
{ $match: { ... } },
{ $group: { ... } }
];

// Executes the aggregation pipeline执行聚合管道
const results = await collection.aggregate(pipeline);
Direct Aggregation直接聚合
// Defines and executes the aggregation pipeline定义并执行聚合管道
const results = await collection.aggregate([
{ $match: { ... } },
{ $group: { ... } }
]);

Aggregation Stage Methods聚合阶段方法

The following table lists the stages in the aggregation pipeline. To learn more about an aggregation stage and see a code example in a Node.js application, follow the link from the stage name to its reference page in the MongoDB Server manual.下表列出了聚合管道中的各个阶段。要了解有关聚合阶段的更多信息并查看Node.js应用程序中的代码示例,请按照MongoDB Server手册中从阶段名称到其参考页面的链接进行操作。

Stage阶段Description描述
$addFields

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

$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 boundaries are automatically determined in an attempt to evenly distribute the documents into the specified number of buckets.根据指定的表达式将传入文档分类到特定数量的组中,称为桶。桶边界是自动确定的,试图将文档均匀地分布到指定数量的桶中。
$changeStream

Returns a change stream cursor for the collection. Must be the first stage in the pipeline.返回集合的更改流游标。必须是管道中的第一阶段。

$changeStream returns an AggregationCursor when passed to the aggregate() method and a ChangeStreamCursor when passed to the watch() method.传递给aggregate()方法时返回AggregationCursor,传递给watch()方法后返回ChangeStreamCursor

$changeStreamSplitLargeEvent

Splits large change stream events that exceed 16 MB into smaller fragments returned in a change stream cursor. Must be the last stage in the pipeline.将超过16MB的大型更改流事件拆分为更改流游标中返回的较小片段。必须是管道中的最后一个阶段。

$changeStreamSplitLargeEvent returns an AggregationCursor when passed to the aggregate() method and a ChangeStreamCursor when passed to the watch() method.传递给aggregate()方法时返回AggregationCursor,传递给watch()方法后返回ChangeStreamCursor

$collStatsReturns statistics regarding a collection or view.返回有关集合或视图的统计信息。
$countReturns a count of the number of documents at this stage of the aggregation pipeline.返回聚合管道此阶段的文档数量计数。
$currentOpReturns a stream of documents containing information on active and dormant operations and any inactive sessions that are holding locks as part of a transaction.返回一个文档流,其中包含有关活动和休眠操作以及作为事务一部分持有锁的任何非活动会话的信息。
$densifyCreates 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.在同一组输入文档的单个阶段内处理多个聚合管道。允许创建能够在单个阶段跨多个维度或方面表征数据的多面聚合。
$geoNearReturns documents in order of nearest to farthest from a specified point. This method adds a field to output documents that contains the distance from the specified point.按离指定点最近到最远的顺序返回文档。此方法在输出文档中添加一个字段,其中包含与指定点的距离。
$graphLookupPerforms a recursive search on a collection. This method adds a new array field to each output document that contains the traversal results of the recursive search for that document.对集合执行递归搜索。此方法向每个输出文档添加一个新的数组字段,该字段包含对该文档的递归搜索的遍历结果。
$groupGroups input documents by a specified identifier expression and applies the accumulator expressions, if specified, to each group. Consumes all input documents and outputs one document per each distinct group. The output documents contain only 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. For each input document, outputs either one document (for the first n documents) or zero documents (after the first n documents).将前n个文档原封不动地传递给管道,其中n是指定的限制。对于每个输入文档,输出一个文档(对于前n个文档)或零个文档(在前n个文件之后)。
$listSampledQueriesLists sampled queries for all collections or a specific collection. Only available for collections with Queryable Encryption enabled.列出所有集合或特定集合的采样查询。仅适用于启用了可查询加密的集合。
$listSearchIndexesReturns information about existing MongoDB Search indexes on a specified collection.返回指定集合上现有MongoDB搜索索引的信息。
$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. For each input document, outputs either one document (a match) or zero documents (no match).筛选文档流,只允许匹配的文档未经修改地传递到下一个管道阶段。对于每个输入文档,输出一个文档(匹配)或零个文档(不匹配)。
$mergeWrites 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 this stage, it must be the last stage in the pipeline.将聚合管道的结果文档写入集合。该阶段可以将结果合并(插入新文档、合并文档、替换文档、保留现有文档、操作失败、使用自定义更新管道处理文档)到输出集合中。要使用此阶段,它必须是管道中的最后一个阶段。
$outWrites the resulting documents of the aggregation pipeline to a collection. To use this stage, it must be the last stage in the pipeline.将聚合管道的结果文档写入集合。要使用此阶段,它必须是管道中的最后一个阶段。
$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. Can be used to implement field level redaction. For each input document, outputs either one or zero documents.根据文档本身存储的信息限制每个文档的内容,从而对流中的每个文档进行重新整形。结合了$project$match的功能。可用于实现字段级编校。对于每个输入文档,输出一个或零个文档。
$replaceRoot

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

The $replaceWith stage is an alias for the $replaceRoot stage.$replaceWith阶段是$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.指定嵌入在输入文档中的文档,以将嵌入的文档提升到顶层。

The $replaceWith stage is an alias for the $replaceRoot stage.$replaceWith阶段是$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集合中的一个或多个字段执行全文搜索。

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

$searchMeta

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

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

$setAdds new fields to documents. Like the Project() method, this method reshapes each document in the stream by adding new fields to output documents that contain both the existing fields from the input documents and the newly added fields.向文档中添加新字段。与Project()方法一样,此方法通过向输出文档添加新字段来重塑流中的每个文档,这些输出文档既包含输入文档中的现有字段,也包含新添加的字段。
$setWindowFieldsGroups documents into windows and applies one or more operators to the documents in each window.将文档分组到窗口中,并对每个窗口中的文档应用一个或多个运算符。
$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. 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.根据指定表达式的值对传入文档进行分组,然后计算每个不同组中的文档计数。
$unionWithCombines pipeline results from two collections into a single result set.将来自两个集合的管道结果合并到一个结果集中。
$unset

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

$unset is an alias for $project 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. n can be zero for an empty array.对于每个输入文档,输出n个文档,其中n是数组元素的数量。对于空数组,n可以为零。
$vectorSearch

Performs an ANN or ENN search on a vector in the specified field of an Atlas collection.Atlas集合的指定字段中对向量执行ANNENN搜索。

This stage is available only for MongoDB Atlas clusters, and is not available for self-managed deployments. To learn more, see MongoDB Vector Search.此阶段仅适用于MongoDB Atlas集群,不适用于自我管理部署。要了解更多信息,请参阅MongoDB矢量搜索

API Documentation文档

To learn more about assembling an aggregation pipeline, see Aggregation Pipeline in the MongoDB Server manual.要了解有关组装聚合管道的更多信息,请参阅MongoDB Server手册中的聚合管道

For more information about the methods and classes used on this page, see the following API documentation:有关此页面上使用的方法和类的更多信息,请参阅以下API文档: