The Symptom
Symptom
Root Cause Analysis
Root Cause
The aggregation pipeline used a `$match`, followed by a `$sort`, and finally a `$group` stage across 5 million records. MongoDB enforces a strict 100MB memory limit per stage for aggregations. Because the `$sort` stage occurred *before* the data was grouped and reduced, it attempted to hold all 5 million full documents in RAM simultaneously, immediately blowing past the 100MB limit.
db.invoices.aggregate([
{ $match: { status: "paid" } },
{ $sort: { createdAt: -1 } }, // FAILS HERE: Trying to sort 5M docs in RAM
{ $group: { _id: "$customerId", total: { $sum: "$amount" } } }
])
Discussions 0