An application frequently queries a collection using equality conditions on 'status' and 'category', followed by a range filter on 'created_at', and sorts the final results by 'priority' descending. How should you design a compound index for optimal performance according to the ESR rule?
Trap 1: { status: 1, category: 1, created_at: 1, priority: -1 }
Placing the range field created_at before the sort field priority violates the ESR rule, forcing MongoDB to perform an in-memory sorting stage after retrieving documents, which degrades performance and memory utilization under heavy application concurrency.
Trap 2: { priority: -1, status: 1, category: 1, created_at: 1 }
Placing the sort field priority before the equality fields status and category prevents the query optimizer from leveraging equality index bounds effectively, resulting in an inefficient index scan that must evaluate unnecessary key combinations.
Trap 3: { created_at: 1, status: 1, category: 1, priority: -1 }
Starting with the range field created_at breaks the ESR rule sequence entirely, forcing MongoDB to scan a much wider index range than necessary before filtering for equality matches and sorting results.
- A
{ status: 1, category: 1, created_at: 1, priority: -1 }
Why it fails: Placing the range field created_at before the sort field priority violates the ESR rule, forcing MongoDB to perform an in-memory sorting stage after retrieving documents, which degrades performance and memory utilization under heavy application concurrency.
- B
{ status: 1, category: 1, priority: -1, created_at: 1 }
Following the ESR rule, the equality fields status and category appear first, followed by the sort field priority, and finally the range field created_at. This structure allows the query engine to efficiently navigate index pointers and satisfy both sorting and range requirements simultaneously without extra sorting.
- C
{ priority: -1, status: 1, category: 1, created_at: 1 }
Why it fails: Placing the sort field priority before the equality fields status and category prevents the query optimizer from leveraging equality index bounds effectively, resulting in an inefficient index scan that must evaluate unnecessary key combinations.
- D
{ created_at: 1, status: 1, category: 1, priority: -1 }
Why it fails: Starting with the range field created_at breaks the ESR rule sequence entirely, forcing MongoDB to scan a much wider index range than necessary before filtering for equality matches and sorting results.