Skip to content
MongoDB

Aggregation Pipeline

Build multi-stage pipelines for analytics.

By EZ4Code Team
aggregationpipelineanalytics

Code

db.orders.aggregate([
  { $match: { status: "completed" } },
  { $group: {
      _id: "$customerId",
      total: { $sum: "$amount" },
      count: { $sum: 1 }
  }},
  { $sort: { total: -1 } },
  { $limit: 10 },
  { $project: {
      customer: "$_id",
      total: 1,
      avgOrder: { $divide: ["$total", "$count"] },
      _id: 0
  }},
  { $lookup: {
      from: "customers",
      localField: "customer",
      foreignField: "_id",
      as: "customerInfo"
  }}
]);

Explanation

The aggregation pipeline chains stages that transform and combine documents. $match filters early for performance, $group computes per-key totals, and $lookup performs a left join with another collection. Order matters: filter and sort before limit to use indexes efficiently.

More MongoDB Snippets