Skip to content

Indexing

Single-field Indexes

The first index you will create, and when it is enough.

IntermediateAbout 4 minutes

A single-field index is enough when the hot query filters (or sorts) on that field alone. { city: 1 } serves find({ city: "Bangalore" }) and sort({ city: 1 }). Direction on a one-field index is almost only about sort order; equality works either way.

db.users.createIndex({ city: 1 })
db.users.find({ city: "Bangalore" })

db.users.createIndex({ isActive: 1 })
db.users.find({ isActive: true })  // often still touches most of the collection
City is selective. isActive alone usually is not.

Selectivity is the point. An index on a boolean, or on status with three values, does not skip much. The planner may still scan. A weak field belongs as a later key in a compound index, not as its own index — next lesson. Nested paths work: { "address.pin": 1 }. One field, one tree.

Interview question

When is a single-field index enough?

Think about it first.

Practice

These filters are the shape a city or role index would serve.