Lesson 23 +10 XP

Indexes

Indexes

An index is a special data structure that makes queries fast. Without an index, MongoDB must scan every document in the collection - a full collection scan. With the right index, it only looks at the matching documents.

The trade-off

  • Indexes speed up reads.
  • They slow down writes - every insert and update must also update the index.
  • Only create indexes for queries you actually run.

How they work

Indexes use a B-tree structure. They store a small portion of the data (the indexed field values) in sorted order, making equality checks, range queries, and sorted results fast.

Types of indexes

Use caseIndex type
Lookups by a single fieldSingle-field index
Lookups by two fields together (name AND quantity)Compound index
ArraysMultikey index
Geospatial queriesGeospatial index (2dsphere)
Text searchText index

The _id index

MongoDB automatically creates a unique index on _id when a collection is created. It prevents two documents from sharing an _id, and you cannot drop it.

Creating an index

// Single-field index on title
db.posts.createIndex({ title: 1 })

// Compound index on category (ascending) and likes (descending)
db.posts.createIndex({ category: 1, likes: -1 })

Inspect and drop indexes

db.posts.getIndexes()   // list indexes
db.posts.dropIndex({ title: 1 })   // remove an index

Naming

An index's default name combines the keys and directions, like category_1_likes_-1.

TL;DR

  • Indexes speed up reads but slow down writes.
  • Types: single-field, compound, multikey, geospatial, text.
  • _id always has a unique, un-droppable index.