Advanced·Scenario·2 min read

MongoDB aggregation becomes slow. What do I check?

Practice this question

Short explanation:

A slow aggregation often processes a much larger intermediate dataset than its final output suggests. Joins, unwinds, sorts and groups can expand work or exceed useful memory limits. Inspecting the pipeline stage by stage reveals where the expensive growth occurs.

Key points:

  • Use explain to inspect scans and expensive stages.

  • Filter earlier where valid; inspect lookup indexes and large sort/group inputs.

  • Return only needed results and compare performance with realistic data.

  • Check changed data distribution and array sizes as well as changed code or missing indexes.

  • Validate that moving a filter does not change the intended group totals or remove required documents.

Interview point:

  • Show how the proposed change reduces examined or intermediate data without changing the report's meaning.
Adapted from 08_PERFORMANCE_SECURITY.md · “3. MongoDB aggregation becomes slow. What do I check?”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.