Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 70 ยท Indexes and performance

Index Types

A tour of MongoDB index types: single field, compound, multikey, text, hashed, geospatial, wildcard, plus partial, sparse, TTL, unique and hidden options.

In How Indexes Work you saw that an index is a sorted structure that lets MongoDB jump to matching documents instead of reading the whole collection. That was one idea, but MongoDB offers many kinds of index, and each one answers a different question: "find by one field", "find by two fields together", "find by any element of an array", "search words", "find nearby places", "expire old data".

This lesson is a guided tour. For each type you will see the real mongosh command, what it is for, and its main limits. Then you will run a small stand-in that builds a compound index as a sorted list, so you can see exactly why the field order matters.

The createIndex commands below are real mongosh commands and are shown read-only. The TryIt blocks use a plain JavaScript stand-in that imitates how a sorted index behaves. It is a teaching model, not MongoDB's B-tree.

Indexes by shape

Single field One field, sorted.
Compound Several fields, in a fixed order.
Multikey One entry per array element.
Hashed Equality only, used for sharding.
1 / 3

Single-field indexes

The simplest index covers one field:

JavaScript
db.users.createIndex({ email: 1 })
db.products.createIndex({ price: -1 })

The 1 means ascending and -1 descending. For a single field the direction does not matter, because MongoDB can walk the index forwards or backwards. The default name is built from the keys, here email_1 and price_-1. You can index a nested field with dot notation, for example { "address.city": 1 }.

A single-field index serves equality ({ email: "[email protected]" }), ranges ({ price: { $lt: 50 } }) and sorts on that field. Every collection already has one automatically: the index on _id.

Compound indexes

A compound index covers several fields in one sorted structure:

JavaScript
db.products.createIndex({ category: 1, price: 1 })

Entries are ordered by category first, and by price within each category, like a phone book sorted by last name and then first name. That ordering has two consequences:

  • A query on category alone can use the index (it uses the first field, a prefix).
  • A query on price alone cannot use it efficiently, because the prices are scattered across all categories.

A compound index can have up to 32 fields. Designing Compound Indexes covers how to pick the order. Here is the idea in action.

JS A compound index is a sorted list

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first two queries examine only the entries inside their bounds (two and four). The price-only query has no usable prefix, so it examines all eight. On eight documents that is nothing; on eighty million it is the difference between milliseconds and minutes.

Multikey indexes

If an indexed field holds an array, MongoDB automatically creates a multikey index with one entry for each element:

JavaScript
db.posts.createIndex({ tags: 1 })
db.posts.find({ tags: "node" })   // matches any post whose tags array contains "node"

You do not declare anything special; the index becomes multikey the first time an array is indexed. Two things to remember:

  • A post with 50 tags creates 50 index entries, so arrays that grow without limit make the index grow too (see Common Performance Pitfalls).
  • In a compound index, at most one of the indexed fields may be an array in any single document ("no parallel arrays").

Text, hashed and geospatial indexes

A text index supports word search with $text:

JavaScript
db.articles.createIndex({ title: "text", body: "text" })
db.articles.find({ $text: { $search: "index performance" } })

A collection can have only one text index, and it tokenises and stems words by language. It is covered in Text Matching and Regular Expressions. For richer search, MongoDB Atlas offers a separate search engine.

A hashed index stores a hash of the value:

JavaScript
db.sessions.createIndex({ userId: "hashed" })

It supports equality lookups only, no ranges and no sorting, because hashing destroys order. Its main use is a hashed shard key that spreads writes evenly (Sharding).

A 2dsphere index supports queries on a sphere such as the Earth, using GeoJSON where longitude comes first:

JavaScript
db.places.createIndex({ location: "2dsphere" })
db.places.find({
  location: {
    $near: {
      $geometry: { type: "Point", coordinates: [13.405, 52.52] },
      $maxDistance: 2000   // metres
    }
  }
})

Operators such as $near, $geoWithin and $geoIntersects rely on it. There is also an older flat 2d index for planar coordinates.

Wildcard indexes

Sometimes you do not know the field names in advance, for example a product whose attributes subdocument holds different keys per category. A wildcard index indexes every field below a path:

JavaScript
db.products.createIndex({ "attributes.$**": 1 })
db.products.find({ "attributes.color": "red" })   // can use the wildcard index

It is convenient for user-defined or unpredictable fields. It is not a replacement for a compound index designed for a known query, so use it when the shape is genuinely open-ended. Schema Design Patterns shows an alternative, the attribute pattern.

Options: unique, partial, sparse, TTL and hidden

These are not index types but properties you add to an index.

Unique rejects duplicate values:

JavaScript
db.users.createIndex({ email: 1 }, { unique: true })

A second document with the same email fails with an E11000 duplicate key error. On a compound index, uniqueness applies to the combination of values. A missing field counts as null, so only one document may omit the field unless you also make the index partial.

Partial indexes cover only documents matching a filter, which makes them smaller and cheaper to maintain:

JavaScript
db.orders.createIndex(
  { customerId: 1 },
  { partialFilterExpression: { status: "open" } }
)

A query can use a partial index only if its own filter guarantees the index condition, so the query must also include status: "open". Combining partial with unique gives "unique when present":

JavaScript
db.users.createIndex(
  { nickname: 1 },
  { unique: true, partialFilterExpression: { nickname: { $exists: true } } }
)

Sparse indexes skip documents that lack the field. They are older than partial indexes, which are more expressive and generally preferred.

TTL (time to live) indexes delete documents automatically:

JavaScript
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })

A background task checks about once a minute and removes documents whose date is older than the limit, so expiry is approximate, not to the second. TTL works on a single date field (see Deleting Documents).

Hidden indexes are kept up to date but ignored by the query planner:

JavaScript
db.orders.hideIndex("status_1")
db.orders.unhideIndex("status_1")

If you suspect an index is unused, hide it, watch performance, and drop it for real only once nothing got slower. Unhiding is instant, while rebuilding a dropped index on a big collection is not.

The next stand-in shows three of these ideas on a tiny collection: how a multikey index grows, how a partial index stays small, and how a unique index rejects a duplicate.

JS Multikey, partial and unique at work

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The multikey list has five entries for four documents, and even documents with an empty or missing tags field get an entry. The partial index skips the draft entirely. The duplicate title is rejected with a message in the style of MongoDB's real E11000 error.

Choosing an index

A practical order of thinking:

  1. Start from your real queries: which fields do they filter on, and how do they sort?
  2. One query on several fields usually wants a compound index, not several single-field ones.
  3. Add unique where the data model demands it, because it enforces a rule, not only speed.
  4. Use partial or TTL when only part of the data needs indexing or the data should expire.
  5. Remember that every index costs disk, memory and write time. Do not index "just in case".

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A compound index on { category: 1, price: 1 } exists. Which query can use it efficiently?

    category is the first field, so it is a usable prefix. A query on price alone has no prefix and would have to look at every entry.
  2. 2. What does MongoDB do when you index a field that contains an array?

    Indexing an array field automatically makes the index multikey, with an entry for each element. Large arrays therefore make large indexes.
  3. 3. Which index type supports only equality lookups, not ranges or sorting?

    A hashed index stores hashes, which have no useful order, so only exact-match lookups work. Its main use is hashed sharding.
  4. 4. You want to find out whether an index is still needed before dropping it. What is the safest first step?

    A hidden index is still maintained but ignored by the planner, so you can test the effect of dropping it and unhide it instantly if something slows down.

Summary

  • A single-field index serves equality, ranges and sorts on one field; _id always has one.
  • A compound index is sorted by its first field, then the next; only a leftmost prefix of its fields is usable on its own.
  • Array fields produce multikey indexes, with one entry per element and a "no parallel arrays" rule for compound indexes.
  • Text, hashed, 2dsphere and wildcard indexes solve word search, equality and sharding, geographic queries and open-ended field names.
  • Unique, partial, sparse, TTL and hidden are options that change what an index enforces, covers, deletes or exposes to the planner.
  • Choose indexes from your real queries, because every index costs writes and memory.

Next, learn to choose the field order in Designing Compound Indexes.