My First Article - What are MongoDB Aggregations?

My First Article - What are MongoDB Aggregations?

Ever wished your database could think a little more like your code? MongoDB Aggregation Pipelines make that wish come true.

Whether you're a MongoDB newbie wondering “What even is an aggregation pipeline?” or a seasoned backend dev trying to optimize reporting queries — this one’s for you.

If you like this article, please do show some love ❤️

What is an Aggregation Pipeline?

MongoDB aggregations are powerful operations used to process data records and return computed results. They allow you to transform, group, filter, and summarize documents in a collection.

Aggregations are operations which can perform complex computations, including SQL’s GROUP BY clauses with functions like SUM, AVG, COUNT, etc., as well as lookups, facets, bucketing, etc.

Aggregations are commonly performed using the Aggregation Pipeline, which consists of multiple stages, each transforming the documents (records) as they pass through the pipeline.

Core Aggregate Stages (aka your must-know stages)

  1. $match – Filter the docs (like WHERE in SQL).
  2. $group – Group docs and do grouped computation (sums, averages, etc).
  3. $project – add/remove/rename fields.
  4. $sort – Sort the results.
  5. $limit / $skip – Paginate like a pro.
  6. $lookup – Perform joins across collections.
  7. $facets - Multiple outputs using a single query to the DB.

And yes, they chain beautifully — up to 100 stages if you’re feeling brave.

Example Use Case

Orders Collection (Sample Data)

Suppose we have an Orders collection like -

[
  {
    "_id": 1,
    "customer": "Alice",
    "items": [
      { "product": "Book", "price": 10, "quantity": 2 },
      { "product": "Pen", "price": 2, "quantity": 5 }
    ]
  },
  {
    "_id": 2,
    "customer": "Bob",
    "items": [
      { "product": "Notebook", "price": 5, "quantity": 6 }
    ]
  },
  {
    "_id": 3,
    "customer": "Charlie",
    "items": [
      { "product": "Pencil", "price": 1, "quantity": 15 },
      { "product": "Eraser", "price": 1, "quantity": 5 }
    ]
  },
  {
    "_id": 4,
    "customer": "Diana",
    "items": [
      { "product": "Bag", "price": 25, "quantity": 1 }
    ]
  }
]        

Now let's say that we have the following use case that we need the output in the single query-

  1. Calculate total spend per customer.
  2. Only consider customers who spent more than $20.
  3. Sort by total spent, descending.
  4. Show only the top 3.

Aggregation Pipeline

db.orders.aggregate([
  { $unwind: "$items" },
  {
    $group: { 
      _id: "$customer",
      totalSpent: {
        $sum: { $multiply: ["$items.price", "$items.quantity"] } 
      }
    }
  },
  { $match: { totalSpent: { $gt: 20 } } },  
  { $sort: { totalSpent: -1 } },  
  { $limit: 3 }  
])        

Now as you saw, we did a whole lot of computations in a single query to the database, which are fully optimised at the DB server level, so that we don’t need to pull all the data and records into our application code and then do all the processing.

What did we do here?

  • $unwind – Break the items array into individual items.
  • $group Group broken items above by customer by adding each product's qty * price
  • $match – Only want customers more than total spend of $20.
  • $sort – Sort by highest spend.
  • $limit – Returns only the top 3.

Output

[
  { "_id": "Alice", "totalSpent": 30 },
  { "_id": "Bob", "totalSpent": 30 },
  { "_id": "Diana", "totalSpent": 25 }
]        

Breakdown

  • Alice: (10×2 + 2×5) = 20 + 10 = 30
  • Bob: (5×6) = 30
  • Charlie: (1×15 + 1×5) = 15 + 5 = 20 → filtered out
  • Diana: (25×1) = 25

In Mongo, you can nest pipelines inside $lookup, $facet, and more. Mind = blown 🤯

Conclusion

As you saw we can do a lot of complicated things with MongoDB Aggregations, including a lot of things that are never possible in SQL world.

If you want to know them, you need to subscribe to this newsletter and show some love ❤️ on this article.



Viny Vincent

Student at Jaramogi Oginga Odinga University of Science and Technology center for E-Learning

2w

Good work Nancy♥️❤️

Like
Reply
DJILI Abdelatif

Systems Engineering and Web Technologies. | Fullstack Web Developper PHP Laravel.

1mo

Good work

Like
Reply
Johnny Reman

Account Executive at Hastings Technology Metals Ltd

1mo

Thanks for sharing 🌹

Like
Reply
Rishika Suri

Senior API developer at NTT DATA, Inc.

2mo

Quick learning. Thankyou Nancy Agarwal

To view or add a comment, sign in

Others also viewed

Explore topics