Sitemap
Manish Prasad

Manish Prasad

Founding Team @Powerplay. Tech leader. IIT Roorkee. AI, Nodejs, Backend Expertise. Exploring life’s journey, one code and one adventure at a time!

Member-only story

Optimize MongoDB Aggregation Pipelines: Common Antipatterns & Performance Tuning

9 min readMar 10, 2026

--

MongoDB aggregation pipelines process documents stage by stage: filter, transform, group, sort. A poorly ordered pipeline on a 1M-document collection can run for 45 second. The same pipeline, restructured, runs in 3 second.

Press enter or click to view image in full size

Reduce the data volume as early as possible in the pipeline

Aggregation pipelines process documents through sequential stages. At small scale the order barely matters. At 500K documents or more, stage order is where most of the time goes.

Pipeline Basics Recap

An aggregation pipeline consists of stages that process documents sequentially:

db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: { _id: "$customerId", total: { $sum: "$amount" } } },
{ $sort: { total: -1 } },
{ $limit: 10 }
]);

Each stage receives the output of the previous one. Understanding execution order is what unlocks optimization.

1. Stage Order Matters

Put $match first. It reduces the document set before any expensive stage runs.

Without Early $match

// Filters after expensive operations
db.orders.aggregate([
{ $unwind…

--

--

Founding Team @Powerplay. Tech leader. IIT Roorkee. AI, Nodejs, Backend Expertise. Exploring life’s journey, one code and one adventure at a time!

See more from me