Search⌘ K
AI Features

Solution: Create a Compound Index

Creating a compound index in MongoDB enhances query performance by indexing multiple fields together. In the example provided, an index on customerId in ascending order and orderDate in descending order significantly reduces the number of documents examined during a query, shifting from a full collection scan to an index scan. This optimization is particularly beneficial for queries that filter by one field and sort by another, thereby improving efficiency in data retrieval.

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:

    ...