3. Single-Field Indexes

A single-field index indexes one field. It is useful when queries frequently filter or sort by that field.

Create an ascending index with db.collection.createIndex({ field: 1 }) and a descending index with { field: -1 }. For a single-field index, MongoDB can often traverse the index in either direction for simple ascending or descending sorts. The direction becomes more important in compound indexes.

A single-field index on status can support eligible filters on status. An index on createdAt can support eligible date-range filters and sorts. Whether an index is beneficial depends on selectivity, query shape, and the amount of data returned.

Before adding an index, examine the application's real filters, sort fields, projection, frequency, and latency requirements.

Code Example
db.orders.createIndex({ status: 1 });
db.orders.createIndex({ createdAt: -1 });

// Check indexes on the collection.
db.orders.getIndexes();
Key Takeaways
  • Single-field indexes support many common filter and sort patterns.
  • The indexed field should match a real query requirement.
  • Use getIndexes() to inspect existing indexes.
  • Validate the benefit with explain and representative data.
Knowledge Check

Which command creates an ascending index on status?