pipeline-stages

For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

<!-- Tab options on this page. Append to the .md URL to filter: ?tabs=<id,...> select specific tabs (e.g. ?tabs=nodejs,shell) ?allTabs=true include every tab (no param) default: one tab per tabset

Available tabs: other tabs: pipeline-definition, pipeline-direct -->

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.

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.

Create a Pipeline

// Defines the aggregation pipeline
const pipeline = [
  { $match: { ... } },
  { $group: { ... } }
];

// Executes the aggregation pipeline
const results = await collection.aggregate(pipeline);

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.

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.
$bucket Categorizes incoming documents into groups, called buckets, based on a specified expression and bucket boundaries.
$bucketAuto Categorizes 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.
$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. $changeStreamSplitLargeEvent returns an AggregationCursor when passed to the aggregate() method and a ChangeStreamCursor when passed to the watch() method.
$collStats Returns statistics regarding a collection or view.
$count Returns a count of the number of documents at this stage of the aggregation pipeline.
$currentOp Returns a stream of documents containing information on active and dormant operations and any inactive sessions that are holding locks as part of a transaction.
$densify Creates new documents in a sequence of documents where certain values in a field are missing.
$documents Returns literal documents from input expressions.
$facet Processes 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.
$geoNear Returns 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.
$graphLookup Performs 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.
$group Groups 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.
$indexStats Returns statistics regarding the use of each index for the collection.
$limit Passes 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).
$listSampledQueries Lists sampled queries for all collections or a specific collection. Only available for collections with Queryable Encryption enabled.
$listSearchIndexes Returns information about existing [MongoDB Search indexes](https://www.mongodb.com/docs/drivers/node/current/indexes.md#std-label-node-indexes-search on a specified collection.
$lookup Performs a left outer join to another collection in the same database to filter in documents from the “joined” collection for processing.
$match Filters 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).
$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 this stage, it must be the last stage in the pipeline.
$out Writes the resulting documents of the aggregation pipeline to a collection. To use this stage, it must be the last stage in the pipeline.
$project Reshapes each document in the stream, such as by adding new fields or removing existing fields. For each input document, outputs one document.
$redact Reshapes 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.
$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. The $replaceWith stage is an alias for the $replaceRoot stage.
$replaceWith 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. The $replaceWith stage is an alias for the $replaceRoot stage.
$sample Randomly selects the specified number of documents from its input.
$search Performs a full-text search of the field or fields in an Atlas collection. 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.
$searchMeta Returns different types of metadata result documents for the MongoDB Search query against an Atlas collection. 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.
$set Adds 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.
$setWindowFields Groups documents into windows and applies one or more operators to the documents in each window.
$skip Skips the first n documents, where n is the specified skip number, and passes the remaining documents unmodified to the pipeline. For each input document, outputs either zero documents (for the first n documents) or one document (if after the first n documents).
$sort Reorders the document stream by a specified sort key. The documents remain unmodified. For each input document, outputs one document.
$sortByCount Groups incoming documents based on the value of a specified expression, then computes the count of documents in each distinct group.
$unionWith Combines 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.
$unwind Deconstructs 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.
$vectorSearch Performs an ANN (Approximate Nearest Neighbor) or ENN (Exact Nearest Neighbor) search on a vector in the specified field of an Atlas collection. This stage is available only for MongoDB Atlas clusters, and is not available for self-managed deployments. To learn more, see [MongoDB Vector Search.](https://www.mongodb.com/docs/drivers/node/current/atlas-vector-search.md#std-label-node-atlas-vector-search

API Documentation

To learn more about assembling an aggregation pipeline, see Aggregation Pipeline in the MongoDB Server manual.

For more information about the methods and classes used on this page, see the following API documentation:

  • Collection

  • [aggregate()](https://mongodb.github.io/node-mongodb-native/7.7/classes/Collection.html#aggregate

  • [watch()](https://mongodb.github.io/node-mongodb-native/7.7/classes/Collection.html#watch

  • AggregateOptions