0Pricing
MongoDB Academy · Lesson

$match and $project: Filter and Reshape

Learners will place $match early in the pipeline for performance and use $project to rename and compute new fields.

The $match Stage

The $match stage is the aggregation pipeline's equivalent of a find() filter. It accepts the same query syntax—equality checks, comparison operators, logical operators, $regex, $elemMatch—and filters the document stream, dropping documents that don't match. Documents that pass flow to the next stage; documents that don't are discarded.

// $match uses the same syntax as find() filters
db.orders.aggregate([
  { $match: {
    status: 'completed',
    amount: { $gte: 100 },
    createdAt: { $gte: new Date('2024-01-01') }
  }}
]);
// Only orders matching ALL three conditions pass through

Place $match First for Index Use

When $match is the first stage in the pipeline, MongoDB can use an index to satisfy the filter—exactly like a find() query. If $match appears after other stages, the index advantage is lost because the planner only pushes index use to the first stage. This is the single most impactful performance rule in aggregation pipeline design.

// GOOD: $match first -> uses index on userId
db.orders.aggregate([
  { $match: { userId: 'u1', status: 'active' } },  // index used here
  { $group: { _id: '$productId', count: { $sum: 1 } } }
]);

// BAD: $match after $group -> full collection scan
db.orders.aggregate([
  { $group: { _id: '$productId', count: { $sum: 1 } } },
  { $match: { userId: 'u1' } }  // too late for index
]);

All lessons in this course

  1. Pipeline Concepts: Stages, Operators, and Expressions
  2. $match and $project: Filter and Reshape
  3. $group: Aggregating and Computing Totals
  4. $sort, $limit, and $skip in the Pipeline
← Back to MongoDB Academy