MongoDB

MongoDB Aggregation Pipeline: The Basics with Examples

5 min read R Square IT Support TeamSample article

Understand $match, $group, $sort, $project and $lookup with simple examples — a frequent topic in MEAN Stack interviews.

The aggregation pipeline processes documents through a sequence of stages, where each stage transforms the documents and passes them to the next — similar to a Unix pipe.

Total sales per category

javascript
db.orders.aggregate([
  { $match: { status: 'DELIVERED' } },
  { $group: { _id: '$category', total: { $sum: '$amount' } } },
  { $sort: { total: -1 } },
  { $project: { _id: 0, category: '$_id', total: 1 } }
]);

Common stages

  • $match — filters documents (place it early to use indexes)
  • $group — groups by a key and calculates totals, averages and counts
  • $project — reshapes documents, includes or excludes fields
  • $sort, $limit, $skip — ordering and pagination
  • $lookup — joins documents from another collection
  • $unwind — deconstructs an array into separate documents
  • MongoDB
  • Aggregation
  • Queries

This is a sample article published as a starter resource. Verify technical details against official documentation for the versions you use.

Prepare. Perform. Progress.

Want personal guidance on this topic?

Our team can help you prepare, solve doubts and practise interviews around what you are learning.

Chat with us