MongoDB Indexes
MongoDB indexes make queries fast by letting the database find matching documents without scanning the whole collection. Every collection has an index on _id; you add others for the fields you filter and sort on.
Creating an Index
createIndex takes the fields and direction (1 ascending, -1 descending).
db.products.createIndex({ category: 1 })
db.products.getIndexes()category_1
[
{ v: 2, key: { _id: 1 }, name: '_id_' },
{ v: 2, key: { category: 1 }, name: 'category_1' }
]Compound Indexes
A compound index covers several fields. Follow the ESR rule: Equality fields first, then Sort fields, then Range fields.
db.products.createIndex({ category: 1, price: -1 })category_1_price_-1
Unique and TTL Indexes
A unique index forbids duplicate values. A TTL index deletes documents automatically after a number of seconds, great for sessions.
db.users.createIndex({ email: 1 }, { unique: true })
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })email_1 createdAt_1
Checking Plans with explain()
explain("executionStats") shows whether a query used an index (IXSCAN) or scanned the collection (COLLSCAN), and how many documents were examined.
db.products.find({ category: "Snacks" }).explain("executionStats").executionStats{
executionSuccess: true,
nReturned: 2,
totalKeysExamined: 2,
totalDocsExamined: 2,
...
}Text Indexes
A text index supports word search with $text.
db.products.createIndex({ name: "text" })
db.products.find({ $text: { $search: "tea" } }, { _id: 0, name: 1 })[ { name: 'Green Tea' } ]Frequently asked questions
How many indexes can a MongoDB collection have?
Up to 64. In practice keep only the indexes your queries use, because each one slows writes and uses memory.
What is the ESR rule?
For compound indexes, place fields used for Equality first, then fields used for Sort, then fields used for Range filters. This lets one index serve the filter and sort efficiently.
How do I drop an index?
Use db.collection.dropIndex("index_name"), for example db.products.dropIndex("category_1").