Knowledge base · Studio 3T Desktop IDE

Supported MongoDB Aggregation Operators and Stages

By Kathryn Vargas · Updated

Aggregation Editor is Studio 3T’s stage-by-stage MongoDB aggregation query builder. Learn more about the feature. This article lists the supported MongoDB Aggregation Operators and stages in the Aggregation Editor. Note that if a stage operator is not listed, it can still be entered into the editor; this list is not exhaustive and only includes stage operators offered by the editor.

All descriptions have been taken from MongoDB’s documentation. You can view the full list of MongoDB aggregation stages here. All aggregation stages are available in MongoDB 3.2 onwards, except where noted.

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

{ $addFields: { <newField>: <expression>, ... } }

$bucket

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

{
  $bucket: {
      groupBy: <expression>,
      boundaries: [ <lowerbound1>, <lowerbound2>, ... ],
      default: <literal>,
      output: {
         <output1>: { <$accumulator expression> },
         ...
         <outputN>: { <$accumulator expression> }
      }
   }
}

$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: {
      groupBy: <expression>,
      buckets: <number>,
      output: {
         <output1>: { <$accumulator expression> },
         ...
      }
      granularity: <string>
  }
}

$collstats

Returns statistics regarding a collection or view.

{
  $collStats:
    {
      latencyStats: { histograms: <boolean> },
      storageStats: { scale: <number> },
      count: {}
    }
}

$count

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

{ $count: <string> }

$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:
   {
      <outputField1>: [ <stage1>, <stage2>, ... ],
      <outputField2>: [ <stage1>, <stage2>, ... ],
      ...

   }
}

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

{ $geoNear: { <geoNear options> } }

$graphLookup

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

{
   $graphLookup: {
      from: <collection>,
      startWith: <expression>,
      connectFromField: <string>,
      connectToField: <string>,
      as: <string>,
      maxDepth: <number>,
      depthField: <string>,
      restrictSearchWithMatch: <document>
   }
}

$group

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

{
  $group:
    {
      _id: <expression>, // Group By Expression
      <field1>: { <accumulator1> : <expression1> },
      ...
    }
 }

$indexStats

Returns statistics regarding the use of each index for the collection.

The $indexStats stage takes an empty document and has the following syntax:

{ $indexStats: { } }

View the full MongoDB documentation.

$limit

Limits the number of documents passed to the next stage in the pipeline.

{ $limit: <positive integer> }

$lookup

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

Equality Match syntax

{
   $lookup:
     {
       from: <collection to join>,
       localField: <field from the input documents>,
       foreignField: <field from the documents of the "from" collection>,
       as: <output array field>
     }
}

Join Conditions and Uncorrelated Sub-queries syntax

{
   $lookup:
     {
       from: <collection to join>,
       let: { <var_1>: <expression>, …, <var_n>: <expression> },
       pipeline: [ <pipeline to execute on the collection to join> ],
       as: <output array field>
     }
}

Correlated Subqueries Using Concise Syntax

Available with MongoDB Server 5.0 and later

{
   $lookup:
      {
         from: <foreign collection>,
         localField: <field from local collection's documents>,
         foreignField: <field from foreign collection's documents>,
         let: { <var_1>: <expression>, …, <var_n>: <expression> },
         pipeline: [ <pipeline to run> ],
         as: <output array field>
      }
}

Read: MongoDB $lookup example.

$match

Filters the documents to pass only the documents that match the specified condition(s) to the next pipeline stage.

{ $match: { <query> } }

$merge

Available with MongoDB Server 4.2 and later

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: {
     into: <collection> -or- { db: <db>, coll: <collection> },
     on: <identifier field> -or- [ <identifier field1>, ...],  // Optional
     let: <variables>,                                         // Optional
     whenMatched: <replace|keepExisting|merge|fail|pipeline>,  // Optional
     whenNotMatched: <insert|discard|fail>                     // Optional
   } 
}

$out

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

Watch the video on YouTube

{ $out: "<output-collection>" }

Read: MongoDB $out example.

$planCacheStats

Available in MongoDB Server 4.2 and later.

Returns plan cache information for a collection. The stage returns a document for each plan cache entry. The $planCacheStats stage must be the first stage in the pipeline and takes an empty document as a parameter.

{ $planCacheStats: { } }

$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: { <specification(s)> } }

Read: MongoDB $project example.

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

{ $redact: <expression> }

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

{ $replaceRoot: { newRoot: <replacementDocument> } }

$replaceWith

Available with MongoDB Server 4.2 and later.

$replaceWith is an alias for $replaceRoot.

{ $replaceWith: <replacementDocument> }

$sample

Randomly selects the specified number of documents from its input.

{ $sample: { size: <positive integer> } }

Available with MongoDB Server 4.2 and later and only available on MongoDB Atlas clusters.

Performs a full-text search of the field or fields in an Atlas collection.

{
  $search: {
    "index": "<index-name>",
    "<operator-name>"|"<collector-name>": {
      <operator-specification>|<collector-specification>
    },
    "highlight": {
      <highlight-options>
    },
    "count": {
      <count-options>
    },
    "returnStoredSource": true | false
  }
}

$set

Available with MongoDB Server 4.2 and later.

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.

$set is an alias for $addFields stage.

{ $set: { <newField>: <expression>, ... } }

$setWindowFields

Available with MongoDB Server 5.0 and later.

Groups documents into windows and applies one or more operators to the documents in each window. Read more about this stage in What is $setWindowFields?

{
   $setWindowFields: {
      partitionBy: <expression>,
      sortBy: {
         <sort field 1>: <sort order>,
         <sort field 2>: <sort order>,
         ...,
         <sort field n>: <sort order>
      },
      output: {
         <output field 1>: {
            <window operator>: <window operator parameters>,
            window: {
               documents: [ <lower boundary>, <upper boundary> ],
               range: [ <lower boundary>, <upper boundary> ],
               unit: <time unit>
            }
         },
         <output field 2>: { ... },
         ...
         <output field n>: { ... }
      }
   }
}

$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: <positive integer> }

$sort

Reorders the document stream by a specified sort key. Only the order changes; the documents remain unmodified. For each input document, outputs one document.

{ $sort: { <field1>: <sort order>, <field2>: <sort order> ... } }

$sortByCount

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

{ $sortByCount:  <expression> }

$unionWith

Available with MongoDB Server 4.4 and later.

Performs a union of two collections. $unionWith combines pipeline results from two collections into a single result set. The stage outputs the combined result set (including duplicates) to the next stage. The order in which the combined result set documents are output is unspecified.

{ $unionWith: { coll: "<collection>", pipeline: [ <stage1>, ... ] } }

$unset

Available with MongoDB Sever 4.2

Removes/excludes fields from documents.$unset is an alias for $project stage that removes fields.

{ $unset: "<field>" }

or

{ $unset: [ "<field1.nestedfield>", ...] }

$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 ndocuments where n is the number of array elements and can be zero for an empty array.

{
  $unwind:
    {
      path: <field path>,
      includeArrayIndex: <string>,
      preserveNullAndEmptyArrays: <boolean>
    }
}

Specialized MongoDB Aggregation Operators

The below are stage operators which have particular requirements or responses and are not generally available in all aggregation pipelines.

$listSessions

Lists all sessions that have been active long enough to propagate to the config databases’s system.sessions collection. This collection must be selected for this stage to be made available in Studio 3T’s aggregation editor.

{ $listSessions: <document> }

Related reading:

With your consent, we and third-party providers use cookies and similar technologies on our website to analyse your use of our site for market research or advertising purposes, including personalized advertising (“performance”), to provide you with additional functions (“functional”), and to show content from social media platforms, such as embedded videos (“social media”). This may result in the creation of pseudonymous usage profiles and the transfer of personal data to third countries, including the USA, which may have no adequate level of protection for the processing of personal data. Please choose for which purposes you wish to give us your consent and store your preferences by clicking on “Accept selected”. You can find further information in section 9 of our Privacy Policy.

Manage consent preferences