Indexes are a crucial part of optimizing query performance in MongoDB. They allow the database to quickly locate and access the data without having to scan every document in a collection. In this section, we will cover the basics of creating indexes, the different types of indexes available, and practical examples to help you understand how to use them effectively.
What is an Index?
An index is a data structure that improves the speed of data retrieval operations on a database table at the cost of additional writes and storage space. In MongoDB, indexes are created on collections and can be used to improve the performance of queries.
Why Use Indexes?
- Improved Query Performance: Indexes can significantly speed up the execution of queries.
- Efficient Sorting: Indexes can be used to sort query results efficiently.
- Unique Constraints: Indexes can enforce unique constraints on the indexed fields.
Types of Indexes
MongoDB supports several types of indexes, including:
- Single Field Index: Indexes a single field of a document.
- Compound Index: Indexes multiple fields of a document.
- Multikey Index: Indexes array fields.
- Text Index: Supports text search queries.
- Geospatial Index: Supports queries for geospatial data.
- Hashed Index: Indexes the hash of the value of a field.
Creating Indexes
Single Field Index
A single field index is the simplest type of index. It indexes a single field in a collection.
1
indicates ascending order.-1
would indicate descending order.
Compound Index
A compound index indexes multiple fields within a document. This can be useful for queries that filter on multiple fields.
// Create a compound index on the "name" and "age" fields of the "users" collection db.users.createIndex({ name: 1, age: -1 });
Multikey Index
A multikey index is used to index array fields. MongoDB creates an index for each element in the array.
// Create a multikey index on the "tags" field of the "posts" collection db.posts.createIndex({ tags: 1 });
Text Index
A text index supports text search queries on string content.
// Create a text index on the "description" field of the "products" collection db.products.createIndex({ description: "text" });
Geospatial Index
A geospatial index supports queries for geospatial data, such as finding documents within a certain distance from a point.
// Create a geospatial index on the "location" field of the "places" collection db.places.createIndex({ location: "2dsphere" });
Hashed Index
A hashed index indexes the hash of the value of a field. This is useful for sharding.
// Create a hashed index on the "user_id" field of the "sessions" collection db.sessions.createIndex({ user_id: "hashed" });
Practical Example
Let's create a practical example to demonstrate the use of indexes. Suppose we have a collection of users, and we want to optimize queries that search for users by their name and age.
Step 1: Insert Sample Data
db.users.insertMany([ { name: "Alice", age: 25, city: "New York" }, { name: "Bob", age: 30, city: "San Francisco" }, { name: "Charlie", age: 35, city: "Los Angeles" }, { name: "David", age: 40, city: "Chicago" } ]);
Step 2: Create an Index
// Create a compound index on the "name" and "age" fields db.users.createIndex({ name: 1, age: 1 });
Step 3: Query with Index
With the index in place, MongoDB can quickly locate the document without scanning the entire collection.
Exercises
Exercise 1: Create a Single Field Index
- Insert sample data into a collection named
products
. - Create a single field index on the
price
field. - Query the collection to find products with a specific price.
Solution
// Step 1: Insert sample data db.products.insertMany([ { name: "Laptop", price: 1000 }, { name: "Phone", price: 500 }, { name: "Tablet", price: 300 } ]); // Step 2: Create a single field index on the "price" field db.products.createIndex({ price: 1 }); // Step 3: Query to find products with a specific price db.products.find({ price: 500 });
Exercise 2: Create a Text Index
- Insert sample data into a collection named
articles
. - Create a text index on the
content
field. - Perform a text search query to find articles containing a specific keyword.
Solution
// Step 1: Insert sample data db.articles.insertMany([ { title: "MongoDB Basics", content: "Learn the basics of MongoDB." }, { title: "Advanced MongoDB", content: "Explore advanced features of MongoDB." }, { title: "MongoDB Indexes", content: "Understand how to create and use indexes in MongoDB." } ]); // Step 2: Create a text index on the "content" field db.articles.createIndex({ content: "text" }); // Step 3: Perform a text search query db.articles.find({ $text: { $search: "indexes" } });
Common Mistakes and Tips
- Over-indexing: Creating too many indexes can slow down write operations. Only create indexes that are necessary for your queries.
- Index Cardinality: Choose fields with high cardinality (many unique values) for indexing to improve query performance.
- Compound Index Order: The order of fields in a compound index matters. Place the most frequently queried fields first.
Conclusion
In this section, we covered the basics of creating indexes in MongoDB, including different types of indexes and practical examples. Indexes are a powerful tool for optimizing query performance, but they should be used judiciously to balance read and write performance. In the next section, we will explore the different types of indexes in more detail.