Skip to content
Studio 3T - The professional GUI, IDE and client for MongoDB
  • Tools
    • Aggregation Editor
    • IntelliShell
    • Visual Query Builder
    • Export Wizard
    • Import Wizard
    • Query Code
    • SQL Query
    • Connect
    • Schema Explorer
    • Compare
    • SQL ⇔ MongoDB Migration
    • Data Masking
    • Task Scheduler
    • Reschema
    • More Tools and Features
  • Solutions
  • Resources
    • Knowledge Base
    • MongoDB Tutorials & Courses
    • Tool/Feature Documentation
    • Reports
    • Case Studies
    • Whitepapers
    • Blog
    • Testimonials
    • Community
  • Contact us
    • Contact
    • Sales Support
    • Feedback and Support
    • Career
    • About Us
  • Store
    • Buy Now
    • Preferred Resellers
    • Team Pricing
  • My License
  • Download
search

Studio 3T Knowledge Base

  • Documentation
  • Tutorials
  • Workshops
Take the fastest route to learning MongoDB. Cover the basics in two hours with MongoDB 101, no registration required.
Start the free course

Supported MongoDB Aggregation Operators and Stages

Posted on: 30/10/2018 (last updated: 10/08/2021) by Kathryn Vargas

Aggregation Editor is Studio 3T’s stage-by-stage MongoDB aggregation query builder. Learn more about the feature.

All descriptions have been taken from MongoDB’s documentation. You can view the full list of MongoDB aggregation stages here.

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

$currentOp

Returns a stream of documents containing information on active and/or dormant operations as well as inactive sessions that are holding locks as part of a transaction. The stage returns a document for each operation or session.

{ $currentOp: { allUsers: <boolean>, idleConnections: <boolean>, idleCursors: <boolean>, idleSessions: <boolean>, localOps: <boolean> } }

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

$listSessions

Lists all sessions that have been active long enough to propagate to the system.sessions collection.

{ $listSessions: <document> }

$listLocalSessions

Lists the sessions cached in memory by the mongod or mongos instance.

{ $listLocalSessions: <document> }

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

Read: MongoDB $lookup example.

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>
     }
}

$match

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

{ $match: { <query> } }

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

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

Read: MongoDB $out example.

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

$sample

Randomly selects the specified number of documents from its input.

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

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

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

Related reading:

  • Aggregation Editor
  • A MongoDB Aggregation Example
  • How to Use the MongoDB Aggregation Framework
  • Extending MongoDB Aggregation with the Bucket and Facet Stages


How helpful was this article?
This article was hideous
This article was bad
This article was ok
This article was good
This article was great
Thank you for your feedback!

About The Author

Kathryn Vargas

When she's not writing about working with MongoDB, Kathryn spends her free time exploring Berlin's food scene, playing the drums, learning languages (current mission: German), and hiking.

Article navigation

Related articles

  • Lesson 5, Exercise 2: Using conditional operators to query embedded documents
  • Exercise 1: Using expression operators to filter input documents
  • MongoDB Aggregation Made Easy with 3T’s Aggregation Editor
  • What’s New in Studio 3T 2021.9 | Popup Visual Query Builder and Aggregation Index Hints
  • Lesson 3, Exercise 3: Adding and removing fields in the aggregation pipeline

Studio 3T

MongoDB Enterprise Certified Technology PartnerSince 2014, 3T has been helping thousands of MongoDB developers and administrators with their everyday jobs by providing the finest MongoDB tools on the market. We guarantee the best compatibility with current and legacy releases of MongoDB, continue to deliver new features with every new software release, and provide high quality support.

Find us on FacebookFind us on TwitterFind us on YouTubeFind us on LinkedIn

Education

  • Free MongoDB Tutorials
  • Connect to MongoDB
  • Connect to MongoDB Atlas
  • Import Data to MongoDB
  • Export MongoDB Data
  • Build Aggregation Queries
  • Query MongoDB with SQL
  • Migrate from SQL to MongoDB

Resources

  • Feedback and Support
  • Sales Support
  • Knowledge Base
  • FAQ
  • Reports
  • Case Studies
  • White Papers
  • Testimonials
  • Discounts

Company

  • About Us
  • Blog
  • Careers
  • Legal
  • Press
  • Privacy Policy
  • EULA

© 2022 3T Software Labs GmbH. All rights reserved.

  • Privacy Policy
  • Cookie settings
  • Impressum
When you click "Accept", you are agreeing to cookies being on your device. They may improve site navigation, site usage analysis, or the relevance of messages. It is up to you which cookies are enabled. Read our Privacy Policy.
Manage cookies
Accept
✕

Privacy Preference Center

A cookie is a small file of letters and numbers that is downloaded on to your computer when you visit a website. Cookies are used by many websites and can do a number of things, eg remembering your preferences, recording what you have put in your shopping basket, and counting the number of people looking at a website. In the form below you can choose which cookies, except for essential cookies, to allow or disable.

Accept all cookies

Manage consent preferences

Essential cookies are strictly necessary to provide an online service such as our website or a service on our website which you have requested. The website or service will not work without them.

Performance cookies allow us to collect information such as number of visits and sources of traffic. This information is used in aggregate form to help us understand how our websites are being used, allowing us to improve both our website’s performance and your experience.

Functional cookies collect information about your preferences and choices and make using the website a lot easier and more relevant. Without these cookies, some of the site functionality may not work as intended.

Social media cookies are cookies used to share user behaviour information with a third-party social media platform. They may consequently effect how social media sites present you with information in the future.

Accept selected