Skip to content

Instantly share code, notes, and snippets.

@immujahidkhan
Created January 7, 2025 11:49
Show Gist options
  • Save immujahidkhan/8b4f0a5e88d3d356f3d15485ad0cd5c7 to your computer and use it in GitHub Desktop.
Save immujahidkhan/8b4f0a5e88d3d356f3d15485ad0cd5c7 to your computer and use it in GitHub Desktop.
Basic aggregation

Mastering MongoDB aggregation requires understanding its powerful operators, pipelines, and stages. Below are the most commonly used aggregation stages and operators with examples:


1. $match

Filters documents to pass only those that match specified conditions.

db.orders.aggregate([
  { $match: { status: "shipped" } }
]);

2. $group

Groups documents by a specified field and performs operations like sum, average, or count.

db.orders.aggregate([
  { $group: { _id: "$customerId", totalAmount: { $sum: "$amount" } } }
]);

3. $project

Shapes the output documents by including, excluding, or transforming fields.

db.orders.aggregate([
  { $project: { orderId: 1, totalCost: { $multiply: ["$price", "$quantity"] } } }
]);

4. $sort

Sorts documents in ascending (1) or descending (-1) order.

db.orders.aggregate([
  { $sort: { createdAt: -1 } }
]);

5. $limit and $skip

Limits the number of documents and skips the specified number of documents.

db.orders.aggregate([
  { $sort: { createdAt: -1 } },
  { $limit: 5 },
  { $skip: 10 }
]);

6. $unwind

Deconstructs an array field to output a document for each element.

db.orders.aggregate([
  { $unwind: "$items" }
]);

7. $lookup

Performs a left outer join with another collection.

db.orders.aggregate([
  {
    $lookup: {
      from: "customers",
      localField: "customerId",
      foreignField: "_id",
      as: "customerDetails"
    }
  }
]);

8. $addFields

Adds or modifies fields in the output documents.

db.orders.aggregate([
  { $addFields: { totalCost: { $multiply: ["$price", "$quantity"] } } }
]);

9. $facet

Processes multiple pipelines and outputs multiple results in one stage.

db.orders.aggregate([
  {
    $facet: {
      totalSales: [{ $group: { _id: null, total: { $sum: "$amount" } } }],
      orderCount: [{ $count: "orderCount" }]
    }
  }
]);

10. $bucket

Categorizes documents into groups, or "buckets," based on a field’s values.

db.orders.aggregate([
  {
    $bucket: {
      groupBy: "$amount",
      boundaries: [0, 50, 100, 200],
      default: "Other",
      output: { count: { $sum: 1 } }
    }
  }
]);

11. $replaceRoot

Replaces the input document with a specified field.

db.orders.aggregate([
  { $replaceRoot: { newRoot: "$customerDetails" } }
]);

12. $out

Writes the results of the aggregation pipeline to a new collection.

db.orders.aggregate([
  { $match: { status: "shipped" } },
  { $out: "shippedOrders" }
]);

Common Operators in Aggregation

  • Arithmetic Operators: $add, $subtract, $multiply, $divide
  • Array Operators: $size, $arrayElemAt, $push
  • Comparison Operators: $eq, $ne, $lt, $lte, $gt, $gte
  • Conditional Operators: $cond, $ifNull
  • String Operators: $concat, $substr, $toUpper, $toLower
  • Date Operators: $dateToString, $dayOfYear, $month, $year

Advanced Example: Comprehensive Aggregation Pipeline

A pipeline to calculate total sales, average order amount, and group by customer.

db.orders.aggregate([
  { $match: { status: "shipped" } },
  {
    $group: {
      _id: "$customerId",
      totalSpent: { $sum: "$amount" },
      averageOrderValue: { $avg: "$amount" },
      orderCount: { $sum: 1 }
    }
  },
  { $sort: { totalSpent: -1 } },
  {
    $lookup: {
      from: "customers",
      localField: "_id",
      foreignField: "_id",
      as: "customerDetails"
    }
  },
  { $project: { _id: 0, customer: { $arrayElemAt: ["$customerDetails.name", 0] }, totalSpent: 1, averageOrderValue: 1, orderCount: 1 } }
]);

Would you like to dive into any specific stage or operator in more detail?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment