MongoDB Indexing

What are Indexes?

Indexes in MongoDB are data structures that improve the speed of data retrieval operations. They are similar to indexes in books, allowing MongoDB to quickly locate documents without scanning the entire collection.

MongoDB Indexing

How Indexes Work in MongoDB

Types of Indexes

Single Field Index

Indexes on a single field of a document.

// Create a single field index
db.users.createIndex({ email: 1 })

// Create a descending index
db.users.createIndex({ age: -1 })

Compound Index

Indexes on multiple fields of a document.

// Create a compound index
db.users.createIndex({ 
    last_name: 1, 
    first_name: 1 
})

Multikey Index

Indexes on array fields.

// Create a multikey index
db.products.createIndex({ 
    tags: 1 
})

Text Index

Indexes for text search operations.

// Create a text index
db.articles.createIndex({ 
    content: "text" 
})

Index Properties

Unique Index

Ensures that no two documents can have the same value for the indexed field.

// Create a unique index
db.users.createIndex({ 
    email: 1 
}, { unique: true })

Sparse Index

Only includes documents that have the indexed field.

// Create a sparse index
db.users.createIndex({ 
    phone: 1 
}, { sparse: true })

TTL Index

Automatically removes documents after a specified period.

// Create a TTL index
db.sessions.createIndex({ 
    createdAt: 1 
}, { expireAfterSeconds: 3600 })

Index Management

Listing Indexes

// List all indexes in a collection
db.users.getIndexes()

// List all indexes in a database
db.getCollectionNames().forEach(function(collection) {
    print("Indexes for " + collection + ":");
    printjson(db[collection].getIndexes());
})

Dropping Indexes

// Drop a specific index
db.users.dropIndex("email_1")

// Drop all indexes
db.users.dropIndexes()

Best Practices

  • Create indexes to support your queries
  • Consider the write/read ratio of your application
  • Monitor index usage and performance
  • Use compound indexes for queries on multiple fields
  • Consider index size and memory usage

Next Steps

Now that you understand indexing, you can explore: