Basic Pipeline Stages in MongoDB

From the MongoDB cheat sheet ยท Aggregation Pipeline ยท verified Jul 2026

Basic Pipeline Stages

Common stages for data transformation

javascript
// Basic aggregation pipeline
db.orders.aggregate([
  { $match: { status: "completed" } },
  { $group: {
    _id: "$customerId",
    totalSpent: { $sum: "$total" },
    orderCount: { $sum: 1 }
  }},
  { $sort: { totalSpent: -1 } },
  { $limit: 10 }
])

// Project (reshape) documents
db.users.aggregate([
  { $project: {
    name: 1,
    email: 1,
    fullName: { $concat: ["$firstName", " ", "$lastName"] },
    age: { $subtract: [
      { $year: new Date() },
      { $year: "$birthDate" }
    ]}
  }}
])
๐ŸŸข Essential - Powerful data processing
๐Ÿ’ก Pipeline stages process sequentially
โšก $match early to reduce documents
๐Ÿ“Œ $group _id can be complex expression
๐Ÿ”— Related: $facet for multiple pipelines
aggregationpipeline

More MongoDB tasks

Back to the full MongoDB cheat sheet