Database Tutorial #11: MongoDB Aggregation Pipeline

find() gets documents. The aggregation pipeline transforms them. It is MongoDB’s answer to SQL GROUP BY, JOIN, and window functions. How the Pipeline Works Documents flow through a sequence of stages. Each stage takes the output of the previous one as input. db.orders.aggregate([ { $match: { status: "delivered" } }, // Stage 1: filter { $group: { _id: "$user_id", total: { $sum: "$amount" } } }, // Stage 2: group { $sort: { total: -1 } }, // Stage 3: sort { $limit: 10 } // Stage 4: limit ]) $match — Filter Documents // Equivalent to WHERE in SQL db.orders.aggregate([ { $match: { status: "delivered", createdAt: { $gte: ISODate("2026-01-01"), $lt: ISODate("2027-01-01") } } } ]) Put $match as early as possible. It reduces the number of documents processed by later stages. ...

August 6, 2026 · 4 min