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
    • Blog
    • Community
    • Testimonials
    • Whitepapers
    • Reports
  • Contact us
    • Contact
    • Sales Support
    • Feedback and Support
    • Careers
    • About Us
  • Store
    • Buy Now
    • Preferred Resellers
    • Team Pricing
  • Download
  • My 3T
search

Academy 3T

  • Explore our courses
    • MongoDB 101: Getting Started
    • MongoDB 201: Querying MongoDB Data
    • MongoDB 301: Aggregation
  • Get certified

Lesson 3: Introducing the MongoDB aggregate method

MongoDB 201: Querying MongoDB Data Working with the MongoDB Aggregation Pipeline Lesson 3: Introducing the MongoDB aggregate method

MongoDB provides the aggregate method for aggregating the data in a collection.

You call the MongoDB aggregate method from a collection object, like you saw with the MongoDB find method in the previous section.

The following syntax shows the basic elements that make up an aggregate statement:

db.getCollection(collection).aggregate(pipeline [, options])

To invoke the aggregate method, you start by specifying the db object, which points to the currently active database.

You then provide the target collection, replacing the collection placeholder with the collection name.

This is followed by the aggregate method and its two arguments, as indicated by the pipeline and options placeholders.

The pipeline placeholder

The pipeline placeholder represents the aggregation pipeline, which is where most of the work occurs.

The pipeline is broken into one or more stages, separated by commas, as shown in the following syntax:

pipeline ::= [stage, ...]

The : : = symbol indicates that the element on the left may expand into or be replaced by the elements on the right.

This symbol is commonly used in formal language notations such as the Backus-Naur Form (BNF). The syntax shown here is a variation of that form.

In this case, it means that the pipeline placeholder can be replaced with one or more stages.

Adding MongoDB aggregation stages

The stages are enclosed in square brackets, indicating that they’re part of an array.

Each stage is an element in that array and is made up of an aggregate method and its expression:

stage ::= { aggregate_method: expression }

A stage definition is enclosed in curly braces, just like a document.

You can think of the pipeline as an array of documents, with each document defining a stage in the pipeline. MongoDB runs the stages in the order specified, each one building on the previous one to produce the final results.

To better understand how this work, consider the following example, which calls the MongoDB aggregate method on the customers collection in the sales database:

use sales;
db.getCollection("customers").aggregate(
  [
    { "$match": { "prio_support": true } }, 
    { "$group": 
      { "_id": "$package", "totals": { "$sum": "$transactions" } } },
    { "$sort": { "_id": 1 } }
  ]
);

The aggregate method includes one argument—the pipeline—which is enclosed in the square brackets. The pipeline defines three stages, each enclosed in curly braces.

Stage 1 uses the $match operator to filter the documents in the pipeline.

The expression assigned to the operator first specifies the field name (prio_support), followed by the desired value (true).

In other words, only documents whose prio_support field value equals true will be passed onto the next stage in the pipeline. All other documents will be filtered out.

Stage 2 uses the $group operator to group the documents by the package field.

The expression for this operator is divided into two parts.

The first part (_id": "$package") indicates that the results should be grouped based on the package field. The _id field is a default field that is used to hold the distinct values that are extracted from the target field, which in this case is package.

The second part of this expression ("totals": { "$sum": "$transactions" }) defines a new field named totals.

The field will hold the total number of transactions for each group.

The number is calculated by using the $sum accumulator operator to add together the values in the transactions field, which is represented by the $transactions alias.

When referencing a field in an aggregate expression, you typically precede the field name with a dollar sign and enclose it in quotes.

Stage 3 uses the $sort operator to sort the documents in the pipeline.

The operator’s expression first specifies the field on which to base the sorting operation and then specifies the sort order.

A value of 1 indicates that the documents should be sorted in ascending order, and a value of -1 indicates that they should be sorted in descending order.

If you run the aggregate statement in IntelliShell, you’ll get the results shown in the following figure. The results include the total number of transactions for each distinct value in the package field.

Aggregate image

The options placeholder

Up to this point, we’ve focused on the MongoDB aggregate method’s pipeline element, which represents the method’s first argument.

However, you can also add an options argument, which includes one or more options that control statement execution.

For example, you can specify an indexing hint or the initial batch size for a cursor. 

The following syntax shows how to specify one or more options:

options ::= { option, ... }

The options are passed to the aggregate method as a document that contains one or more fields, which define the option settings. Each field consists of an option name and its value, as shown in the following syntax:

option ::= option_name: option_value

The format of the option value depends on which option you’re setting. It might be a simple scalar value, such as false, or a more complex expression.

If you include multiple options, you must separate them with commas. The following code includes the same aggregate statement as in the previous example, only now it contains two options, which are added after the pipeline:

use sales;
db.getCollection("customers").aggregate(
  [
    { "$match": { "prio_support": true } }, 
    { "$group": 
      { "_id": "$package", "totals": { "$sum": "$transactions" } } },
    { "$sort": { "_id": 1.0 } }
  ],
  {
    "allowDiskUse": true , 
    "collation":
      { "locale" : "en_US", "strength": 1 }
  }
);

The first option sets the allowDiskUse setting to true, which enables the aggregation operations to write data to temporary files on disk.

The second option sets the collation settings, which can take multiple values.

In this case, the locale value is set to en_US (United States English), and the strength value is set to 1, which means collation comparisons are limited to the base characters only.

Overall, this is a relatively simple aggregate statement, but such statements can get quite complex. Fortunately, Studio 3T provides the Aggregation Editor for simplifying this process.

The Aggregation Editor walks you through the steps necessary to create aggregations. Not only does this simplify the process of defining aggregations, but it also serves as a tool for learning how to construct aggregate statements so you have a better sense of how they work.

Previous Lesson
Back to Lesson
Next Topic
  • Course Home Expand All
    Performing MongoDB CRUD Operations
    4 Topics | 1 Quiz
    Lesson 1, Exercise 1: Adding a document to a collection
    Lesson 1, Exercise 2: Viewing a document in a collection
    Lesson 1, Exercise 3: Updating a document in a collection
    Lesson 1, Exercise 4: Deleting a document from a collection
    Test your skills: Performing CRUD Operations
    Building MongoDB find() Queries
    4 Topics | 1 Quiz
    Lesson 2: The MongoDB find method
    Lesson 2, Exercise 1: Using IntelliShell to build and run find statements
    Lesson 2, Exercise 2: Using Visual Query Builder to build and run find statements
    Lesson 2, Exercise 3: Using Query Code and IntelliShell to modify and run a find statement
    Test your skills: Building MongoDB find() Queries
    Working with the MongoDB Aggregation Pipeline
    6 Topics | 1 Quiz
    Lesson 3: Introducing the MongoDB aggregate method
    Lesson 3, Exercise 1: Filtering the documents in the aggregation pipeline
    Lesson 3, Exercise 2: Grouping the documents in the aggregation pipeline
    Lesson 3, Exercise 3: Adding and removing fields in the aggregation pipeline
    Lesson 3, Exercise 4: Changing the field order in the aggregation pipeline
    Lesson 3, Exercise 5: Sorting the documents in the aggregation pipeline
    Test your skills: Working with the MongoDB Aggregation Pipeline
    Querying Arrays Using MongoDB $elemMatch
    4 Topics | 1 Quiz
    Lesson 4, Exercise 1: Using IntelliShell to query single and multiple values in an array
    Lesson 4, Exercise 2: Using Visual Query Builder to query a single array value
    Lesson 4, Exercise 3: Using Visual Query Builder to query multiple array values
    Test your skills: Querying Arrays Using MongoDB $elemMatch
    MongoDB 201 Mid-Course Feedback
    Querying Embedded Documents in MongoDB Arrays
    3 Topics | 1 Quiz
    Lesson 5, Exercise 1: Using the $elemMatch operator to query embedded documents
    Lesson 5, Exercise 2: Using conditional operators to query embedded documents
    Lesson 5, Exercise 3: Using Visual Query Builder to query embedded documents
    Test your skills: Querying Embedded Documents in Arrays
    Querying MongoDB with SQL SELECT Statements
    2 Topics | 1 Quiz
    Lesson 6, Exercise 1: Using the SQL Query tool to run SQL statements
    Lesson 6, Exercise 2: Using the SQL Query tool to aggregate collection data
    Test your skills: Querying MongoDB with SQL
    Working with MongoDB Views
    3 Topics | 1 Quiz
    Lesson 7, Exercise 1: Creating a MongoDB view
    Lesson 7, Exercise 2: Querying a MongoDB view
    Lesson 7, Exercise 3: Modifying and deleting a MongoDB view
    Test your skills: Working with MongoDB Views
    Course Extras
    Return to MongoDB 201: Querying MongoDB Data
  • 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
    • White Papers
    • Testimonials
    • Discounts

    Company

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

    © 2023 3T Software Labs Ltd. All rights reserved.

    • Privacy Policy
    • Cookie settings
    • Impressum

    We value your privacy

    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 ("analytics and marketing") and to provide you with additional functions (“functional”). 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.

    By clicking “Accept all”, you consent to the storage of cookies and the processing of personal data for these purposes, including any transfers to third countries. By clicking on “Decline all”, you do not give your consent and we will only store cookies that are necessary for our website. You can customize the cookies we store on your device or change your selection at any time - thus also revoking your consent with effect for the future - under “Manage Cookies”, or “Cookie Settings” at the bottom of the page. You can find further information in our Privacy Policy.
    Accept all
    Decline all
    Manage cookies
    ✕

    Privacy Preference Center

    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 ("analytics and marketing") and to provide you with additional functions (“functional”). 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 our Privacy Policy.

    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.

    Google Analytics

    Google Ads

    Bing Ads

    Facebook

    LinkedIn

    Quora

    Hotjar

    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.

    HubSpot

    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