MyInternships.in

Databases & Data Access

Node.js MongoDB Aggregation

The aggregation pipeline processes documents through stages — match, group, sort, project, lookup — and is how you compute totals, averages, groupings and joins inside MongoDB rather than in application code.


What is MongoDB Aggregation in Node.js?

The aggregation pipeline processes documents through stages — match, group, sort, project, lookup — and is how you compute totals, averages, groupings and joins inside MongoDB rather than in application code.

MongoDB Aggregation example

Average stipend per city
JavaScript
const stats = await Job.aggregate([
  { $match: { status: 'active', stipend: { $gt: 0 } } },   // filter FIRST
  { $group: {
      _id: '$city',
      avgStipend: { $avg: '$stipend' },
      maxStipend: { $max: '$stipend' },
      count: { $sum: 1 },
  } },
  { $match: { count: { $gte: 5 } } },
  { $sort: { avgStipend: -1 } },
  { $limit: 10 },
  { $project: { _id: 0, city: '$_id', avgStipend: { $round: ['$avgStipend', 0] }, count: 1 } },
]);

How this works

Putting $match first is the single most important optimisation: it uses indexes and shrinks the document set before the expensive grouping stage runs.

Key points to remember

  • $match early, $project late — reduce documents before doing work on them.
  • $lookup performs a left outer join with another collection.
  • $unwind expands an array field into one document per element.
  • Aggregation bypasses Mongoose schema casting — values come back raw.

Common mistakes with MongoDB Aggregation

  • $match placed after $group, so the whole collection is grouped first.
  • Pipelines that exceed the 100 MB memory limit without allowDiskUse.

Node.js MongoDB Aggregation— Interview Questions & FAQs

When should I use aggregation instead of find?+

Whenever you need grouping, totals, averages, joins across collections, or reshaping documents. Doing that work in JavaScript means transferring far more data than necessary.

Related Node.js Topics

Keep learning with these closely related lessons.

Ready to use your Node.js skills?

Find verified Node.js internships and fresher developer jobs across India.

Browse Node.js Internships