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: empty-pipeline-definition, aggregate -->

Aggregation Pipeline Stages

Overview

On this page, you can learn how to create an aggregation pipeline and pipeline stages by using methods in the .NET/C# Driver.

Build an Aggregation Pipeline

You can use the .NET/C# Driver to build an aggregation pipeline by using builder methods or BSON documents. See the following sections to learn more about each of these approaches.

Builder Methods

You can build a type-safe aggregation pipeline in the following ways:

  • Construct an EmptyPipelineDefinition<TDocument> object. Chain calls from this object to the relevant aggregation methods. Then, pass the pipeline object to the IMongoCollection<TDocument>.Aggregate() method.

  • Call the IMongoCollection<TDocument>.Aggregate() method. Chain calls from this method call to the relevant aggregation methods.

Select the EmptyPipelineDefinition or Aggregate tab to see the corresponding code for each approach:

EmptyPipelineDefinition

// Defines the aggregation pipeline
var pipeline = new EmptyPipelineDefinition<Movie>()
   .Match(...)
   .Group(...)
   .Merge(...);

// Executes the aggregation pipeline
var results = collection.Aggregate(pipeline);

BsonDocument

Some aggregation stages don't have corresponding methods in the .NET/C# Driver. To add these stages to your pipeline, use BsonDocument objects or string literals to construct a stage in the Query API syntax. Then, pass the BSON document to the PipelineDefinitionBuilder.AppendStage() method. This syntax supports all stages in the aggregation pipeline, but doesn't provide type hints or type safety.

The following code example shows how to add the $unset stage to an empty aggregation pipeline:

var pipeline = new EmptyPipelineDefinition<BsonDocument>()
        .AppendStage<BsonDocument, BsonDocument, BsonDocument>("{ $unset: 'field1' }");

Important:

If you use a BsonDocument to define a pipeline stage, the driver doesn't recognize any BsonClassMap attributes, serialization attributes, or serialization conventions. The field names that you use in the BsonDocument must match the field names stored in MongoDB Server.

Aggregation Stage Methods

The following table lists the builder methods in the .NET/C# Driver that correspond to stages in the aggregation pipeline. To learn more about an aggregation stage and see a code example for the equivalent C# method, follow the link from the stage name to its reference page in the MongoDB Server manual.

If an aggregation stage isn't in the table, the driver doesn't provide a builder method for it. In this case, you must use the [BsonDocument](https://www.mongodb.com/docs/drivers/csharp/current/aggregation/stages.md#std-label-csharp-aggregation-stages-bsondocument syntax to add the stage to your pipeline.

Aggregation Stage Description Builder Method
$bucket Categorizes incoming documents into groups, called buckets, based on a specified expression and bucket boundaries. Bucket()
$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. BucketAuto()
$changeStream Returns a change stream cursor for the collection. This stage can occur only once in an aggregation pipeline and it must occur as the first stage. ChangeStream()
$changeStreamSplitLargeEvent Splits large change stream events that exceed 16 MB into smaller fragments returned in a change stream cursor. You can use $changeStreamSplitLargeEvent only in a $changeStream pipeline, and it must be the final stage in the pipeline. ChangeStreamSplitLargeEvent()
$count Returns a count of the number of documents at this stage of the aggregation pipeline. Count()
$densify Creates new documents in a sequence of documents where certain values in a field are missing. Densify()
$documents Returns literal documents from input expressions. Documents()
$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. Facet()
$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. GeoNear()
$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. GraphLookup()
$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. Group()
$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). Limit()
$lookup Performs a left outer join to another collection in the same database to filter in documents from the “joined” collection for processing. Lookup()
$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). 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. Merge()
$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. Out()
$project Reshapes each document in the stream, such as by adding new fields or removing existing fields. For each input document, outputs one document. Project()
$rankFusion Uses a rank fusion algorithm to combine results from a MongoDB Vector Search query and a MongoDB Search query. RankFusion()
$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. ReplaceRoot()
$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. ReplaceWith()
$rerank Reorders input documents by using Voyage AI's reranking models and returns the same documents sorted by relevance. You can use this stage anywhere in an aggregation pipeline, but we recommend using it after a $vectorSearch, $search, $rankFusion, or $scoreFusion stage. Rerank()
$sample Randomly selects the specified number of documents from its input. Sample()
$search Performs a full-text search of the field or fields in an Atlas collection. To learn more, see MongoDB Search Aggregation Pipeline Stages in the Atlas documentation. Search()
$searchMeta Returns different types of metadata result documents for the MongoDB Search query against an Atlas collection. To learn more, see MongoDB Search Aggregation Pipeline Stages in the Atlas documentation. SearchMeta()
$set Sets the value of an existing field. You cannot use this method to add a new document field. Set()
$setWindowFields Groups documents into windows and applies one or more operators to the documents in each window. SetWindowFields()
$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). Skip()
$sort Reorders the document stream by a specified sort key. The documents remain unmodified. For each input document, outputs one document. Sort()
$sortByCount Groups incoming documents based on the value of a specified expression, then computes the count of documents in each distinct group. SortByCount()
$unionWith Combines pipeline results from two collections into a single result set. UnionWith()
$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. Unwind()
$vectorSearch Performs an ANN (Approximate Nearest Neighbor) or ENN (Exact Nearest Neighbor) search on a vector in the specified field of an Atlas collection. To learn more, see [MongoDB Vector Search.](https://www.mongodb.com/docs/drivers/csharp/current/atlas-vector-search.md#std-label-csharp-atlas-vector-search VectorSearch()

API Documentation

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

To learn more about creating pipeline stages, see Aggregation Stages in the MongoDB Server manual.

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