Indexes Intro

View saved

Why indexes exist

Without an index, MongoDB may scan many documents. An index is a sorted structure that helps locate matching values faster.

Create a simple index

Index fields you filter or sort on often.

db.books.createIndex({ title: 1 })
db.books.createIndex({ year: -1, title: 1 })

Unique indexes

Enforce uniqueness—for example, one email per user.

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

Inspect and trim

List indexes and drop ones you no longer need. Extra indexes slow writes and use disk.

db.books.getIndexes()
// db.books.dropIndex({ title: 1 })

Comments

One comment per signed-in account. Comments are saved with this page’s URL.