A compound index helps you find data faster when you search using more than one field. The order of fields in the index matters because it changes how quickly you get results.
Compound index and field order in MongoDB
db.collection.createIndex({ field1: 1, field2: -1 })Use 1 for ascending order and -1 for descending order.
The order of fields in the index affects which queries can use it efficiently.
db.products.createIndex({ category: 1, price: 1 })db.orders.createIndex({ customerId: 1, orderDate: -1 })db.users.createIndex({ lastName: 1, firstName: 1 })First, we create a compound index on region (ascending) and salesAmount (descending). Then, we find sales in the 'West' region and sort them by salesAmount from highest to lowest. The index helps this query run faster.
db.sales.createIndex({ region: 1, salesAmount: -1 })
db.sales.find({ region: 'West' }).sort({ salesAmount: -1 })If you search only by the first field in the compound index, MongoDB can still use the index efficiently.
But if you search only by the second field, the index is not helpful.
Think of the index like a phone book sorted first by last name, then by first name.
Compound indexes speed up queries using multiple fields together.
The order of fields in the index matters for query performance.
Use ascending (1) or descending (-1) to control sorting in the index.