What is Index in MongoDB: Explanation and Examples
index is a special data structure that improves the speed of data retrieval operations on a collection. It works like an index in a book, helping MongoDB find data quickly without scanning every document.How It Works
Think of an index in MongoDB like the index at the back of a book. Instead of flipping through every page to find a topic, you look at the index to find the exact page number. Similarly, MongoDB uses indexes to quickly locate documents without scanning the entire collection.
When you create an index on a field, MongoDB builds a sorted list of the values in that field along with pointers to the documents that contain those values. This makes searching, sorting, and filtering much faster, especially for large collections.
Example
This example shows how to create an index on the name field of a collection and then query using that index.
use mydatabase
db.users.insertMany([
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 35 }
])
db.users.createIndex({ name: 1 })
// Query using the indexed field
db.users.find({ name: "Alice" })When to Use
Use indexes in MongoDB when you want to speed up queries that filter or sort by specific fields. For example, if your application often searches users by their email or sorts products by price, adding indexes on those fields will make these operations faster.
However, indexes take extra space and slow down write operations like inserts and updates, so only add indexes on fields you query frequently.
Key Points
- Indexes improve query speed by avoiding full collection scans.
- They work like a book's index, mapping field values to document locations.
- Creating indexes on frequently queried fields is beneficial.
- Too many indexes can slow down writes and use more storage.