intermediateMongoDB — CRUD, Queries & Aggregation Framework
A MongoDB aggregation pipeline on 50 million documents takes 30 seconds. How do you optimize it?
Step 1: Check current execution: db.orders.aggregate([...], {explain: 'executionStats'}). Step 2: Move $match to the FIRST stage — filters data early. Step 3: Ensure an index exists for all $match fields: db.orders.createIndex({status:1, createdAt:-1}). Step 4: Add $project early to reduce document size flowing through pipeline. Step 5: For very large pipelines: allowDiskUse: true (but this signal
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response