Docs Menu
Docs Home
/ / /
C#/.NET
/

Aggregation Pipeline Stages

On this page

  • Overview
  • Build an Aggregation Pipeline
  • Builder Methods
  • BsonDocument
  • Aggregation Stage Methods
  • API Documentation

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

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.

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:

// Defines the aggregation pipeline
var pipeline = new EmptyPipelineDefinition<Movie>()
.Match(...)
.Group(...)
.Merge(...);
// Executes the aggregation pipeline
var results = collection.Aggregate(pipeline);
// Defines and executes the aggregation pipeline
var results = collection.Aggregate()
.Match(...)
.Group(...)
.Merge(...);

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.

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, follow the link from the method name to its reference page in the MongoDB Server manual. To learn more about a builder method, follow the link from the method name to its dedicated page.

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 syntax to add the stage to your pipeline.

Aggregation Stage
Description
Builder Method

Categorizes incoming documents into groups, called buckets, based on a specified expression and bucket boundaries.

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.

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.

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.

Returns a count of the number of documents at this stage of the aggregation pipeline.

Creates new documents in a sequence of documents where certain values in a field are missing.

Returns literal documents from input expressions.

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.

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.

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.

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).

Performs a left outer join to another collection in the same database to filter in documents from the "joined" collection for processing.

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).

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.

Writes the resulting documents of the aggregation pipeline to a collection. To use this stage, it must be the last stage in the pipeline.

Reshapes each document in the stream, such as by adding new fields or removing existing fields. For each input document, outputs one document.

Uses a rank fusion algorithm to combine results from a Vector Search query and an Atlas Search query.

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.

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.

Randomly selects the specified number of documents from its input.

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 Atlas Search Aggregation Pipeline Stages in the Atlas documentation.

Returns different types of metadata result documents for the Atlas 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 Atlas Search Aggregation Pipeline Stages in the Atlas documentation.

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.

Groups documents into windows and applies one or more operators to the documents in each window.

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).

Reorders the document stream by a specified sort key. The documents remain unmodified. For each input document, outputs one document.

Groups incoming documents based on the value of a specified expression, then computes the count of documents in each distinct group.

Combines pipeline results from two collections into a single result set.

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.

Performs an ANN or ENN 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 Atlas Vector Search.

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:

Back

Aggregation