Search⌘ K
AI Features

Solution: Create a Compound Index

We'll cover the following...
Query
/* Find an order's detail */
db.orders.find({
customerId: "f9437b18a248488827a75532",
orderDate: { $gte: ISODate("2025-01-01T00:00:00Z") }
}).sort({ orderDate: -1 }).explain("executionStats"),
/*Create the compound index here*/
db.orders.createIndex(
{
customerId: 1,
orderDate: -1
}
),
/* Now, again find an order's detail */
db.orders.find({
customerId: "f9437b18a248488827a75532",
orderDate: { $gte: ISODate("2025-01-01T00:00:00Z") }
}).sort({ orderDate: -1 }).explain("executionStats")

The explanation of the query is given below:

  • Lines 2–5: The find() query finds all orders for a specific customer placed on or after Jan 1, 2025, and returns them sorted from newest to oldest. The explain("executionStats") explains three main key points:

    • This query does the complete ...