← All posts

MongoDB Aggregation Basics: Core Concepts and Examples

mongodbdatabaseaggregationnosql

Among NoSQL databases, MongoDB stands out for its powerful data processing features. The aggregation pipeline is the core tool in MongoDB for transforming, grouping and analyzing data. In this post we'll go over the core concepts of the MongoDB aggregation pipeline, its most common stages and how it works through practical examples.

What Is the Aggregation Pipeline?

The aggregation pipeline transforms data in MongoDB by passing it through a series of processing stages. Each stage processes the documents and hands the result to the next stage. This makes complex data analysis and summaries easy to do.

Common Aggregation Stages

  1. $match: Filters data, similar to the WHERE clause in SQL.
  2. $group: Groups documents by a key and computes summaries.
  3. $sort: Sorts the results by a given field.
  4. $project: Decides which fields go into the output, or creates new fields.
  5. $lookup: Combines data from different collections, similar to a JOIN in SQL.
  6. $addFields: Adds new fields to your documents or transforms existing ones.

Example 1: Filtering and Grouping

Say you have an orders collection, and each order has a customer ID (customerId), a total amount (total) and a date (date). You want to calculate the total order amount per customer:

mongoshjs
db.orders.aggregate([
  { $match: { date: { $gte: ISODate("2025-01-01") } } },
  { $group: { _id: "$customerId", totalSpent: { $sum: "$total" } } },
  { $sort: { totalSpent: -1 } },
]);
  • $match: Filters orders from 2025 onward.
  • $group: Groups by customer and calculates the total spent.
  • $sort: Sorts the results by total spent in descending order.

Example 2: Transforming and Filtering Fields

A users collection holds users' names (name) and ages (age). You want only the names of users older than 30:

mongoshjs
db.users.aggregate([
  { $match: { age: { $gt: 30 } } },
  { $project: { name: 1, _id: 0 } },
]);
  • $match: Selects users older than 30.
  • $project: Returns only the name field and excludes _id.

Example 3: Joining Data with $lookup

$lookup is used to relate different collections. For example, you want to pull customer details for the orders in the orders collection from the customers collection:

mongoshjs
db.orders.aggregate([
  { $match: { date: { $gte: ISODate("2025-01-01") } } },
  {
    $lookup: {
      from: "customers",
      localField: "customerId",
      foreignField: "_id",
      as: "customerInfo",
    },
  },
  { $project: { customerInfo: { name: 1 }, total: 1, _id: 0 } },
]);
  • $match: Filters orders from 2025 onward.
  • $lookup: Matches customerId in the orders collection with _id in the customers collection and adds the customer details to the customerInfo array.
  • $project: Returns only the customer name and the order total.

Example 4: Adding a New Field with $addFields

You want to calculate a tax field (tax) for each order in the orders collection and add it. Let's say the tax is 10% of the total:

mongoshjs
db.orders.aggregate([
  { $match: { date: { $gte: ISODate("2025-01-01") } } },
  { $addFields: { tax: { $multiply: ["$total", 0.1] } } },
  { $project: { customerId: 1, total: 1, tax: 1, _id: 0 } },
]);
  • $match: Filters orders from 2025 onward.
  • $addFields: Adds a tax field to each document, set to 10% of total.
  • $project: Returns the customer ID, total and tax fields.

Advantages and Use Cases of Aggregation

The aggregation pipeline makes analysis on large datasets easier. For example:

  • Reporting: Summarizing sales data.
  • Joining Data: Bringing together data from different collections.
  • Transforming Data: Converting documents into a different shape or adding new fields.
  • Filtering and Analysis: Building subsets of data with complex queries.

When Should You Use It?

Aggregation comes into play once you go beyond simple queries. When you need to group, join, summarize or transform your data, the aggregation pipeline is a great choice. Optimizing the pipeline matters for performance. For example, putting the $match stage first to shrink the dataset early pays off.

Conclusion

The MongoDB aggregation pipeline is an essential tool for processing data in a flexible and powerful way. Stages like $match, $group, $sort, $project, $lookup and $addFields turn complex analysis into a simple flow. By combining these stages to fit your project's needs, you can get the most out of your data.