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.
How Indexes Work in MongoDB
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 })
Indexes on multiple fields of a document.
// Create a compound index
db.users.createIndex({
last_name: 1,
first_name: 1
})
Indexes on array fields.
// Create a multikey index
db.products.createIndex({
tags: 1
})
Indexes for text search operations.
// Create a text index
db.articles.createIndex({
content: "text"
})
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 })
Only includes documents that have the indexed field.
// Create a sparse index
db.users.createIndex({
phone: 1
}, { sparse: true })
Automatically removes documents after a specified period.
// Create a TTL index
db.sessions.createIndex({
createdAt: 1
}, { expireAfterSeconds: 3600 })
// 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());
})
// Drop a specific index
db.users.dropIndex("email_1")
// Drop all indexes
db.users.dropIndexes()
Now that you understand indexing, you can explore: