Lecture Notes Of Day 9: Indexes in MongoDB
Objective:
- To
understand indexing in MongoDB and how it helps in improving query
performance.
- To
learn how to create, view, and delete indexes in MongoDB.
Outcome:
- By
the end of this lesson, students will be able to:
1. Understand
the concept of indexing in MongoDB.
2. Create
indexes on collections.
3. View the
existing indexes in a collection.
4. Drop
(delete) indexes when they are no longer needed.
Introduction
to Indexes:
In MongoDB, an index is a
data structure that improves the speed of data retrieval operations on a
collection. Without indexes, MongoDB must perform a full scan of the collection
(also called a collection scan) to locate documents that match the query
conditions. As the collection grows larger, collection scans can become slow
and inefficient.
Why Use
Indexes?
1. Faster
Query Performance:
o
Indexes significantly improve query performance by
reducing the need to scan all documents in a collection.
2. Efficient
Sorting:
o
Indexes allow MongoDB to quickly sort query results
without scanning the entire collection.
3. Optimize
Queries with Specific Conditions:
o
Indexes help in queries that use operators like $eq,
$gt, $lt, $in, $regex, etc.
Types of
Indexes in MongoDB:
1. Single
Field Index:
o
This index is created on a single field and is the
most common type of index.
Example:
javascript
CopyEdit
db.collection.createIndex({
fieldName: 1 });
o
The 1 represents ascending order. Use -1 for
descending order.
2. Compound
Index:
o
An index created on multiple fields to support
queries that require sorting or filtering on multiple fields.
Example:
javascript
CopyEdit
db.collection.createIndex({
field1: 1, field2: -1 });
3. Multikey
Index:
o
MongoDB automatically creates a multikey index when
a field contains an array. This index is used to efficiently query array
values.
4. Text
Index:
o
Used for full-text search on string content.
Example:
javascript
CopyEdit
db.collection.createIndex({
fieldName: "text" });
5. Hashed
Index:
o
Used for sharding and to distribute documents
evenly across a sharded cluster.
Example:
javascript
CopyEdit
db.collection.createIndex({
fieldName: "hashed" });
6. Geospatial
Index:
o
Used to support geospatial queries (e.g.,
location-based searches).
Example:
javascript
CopyEdit
db.collection.createIndex({
location: "2dsphere" });
Creating
Indexes:
To create an index in MongoDB,
you use the createIndex() method. This method allows you to specify the fields
for which you want to create the index, as well as the sorting order (ascending
or descending).
Example
1: Creating a Single Field Index
Create an index on the name field
of a collection:
javascript
CopyEdit
db.users.createIndex({
name: 1 });
This index will sort the name
field in ascending order.
Example
2: Creating a Compound Index
Create an index on both the name
and age fields:
javascript
CopyEdit
db.users.createIndex({
name: 1, age: -1 });
This index will sort the name
field in ascending order and age in descending order.
Viewing
Indexes:
To view all indexes in a
collection, use the getIndexes() method. This method returns an array of the
indexes defined on the collection.
javascript
CopyEdit
db.collection.getIndexes();
Example:
javascript
CopyEdit
db.users.getIndexes();
This will return a list of
indexes for the users collection, including the default _id index and any
custom indexes created.
Dropping
(Deleting) Indexes:
If an index is no longer needed
or if you want to free up resources, you can delete the index using the dropIndex()
method. You can drop a specific index by name or by specification.
Example
1: Dropping an Index by Name
javascript
CopyEdit
db.users.dropIndex("name_1");
Example
2: Dropping an Index by Specification
javascript
CopyEdit
db.users.dropIndex({
name: 1 });
Example
3: Dropping All Indexes Except the Default _id Index
javascript
CopyEdit
db.users.dropIndexes();
Best
Practices for Indexing:
1. Create
Indexes Based on Query Patterns:
o
Index only the fields that are frequently used in
queries, sorting, or filtering. Over-indexing can slow down write operations.
2. Use
Compound Indexes for Complex Queries:
o
When a query involves multiple fields, use compound
indexes to improve query performance.
3. Consider
Using Indexes for Sort Operations:
o
Index the fields that are frequently used for
sorting to improve performance.
4. Regularly
Monitor Index Usage:
o
Use db.collection.stats() to monitor index usage
and determine if any indexes can be removed.
5. Be
Cautious with Multikey Indexes:
o
Multikey indexes can be useful but should be used
carefully as they can become large and impact performance for certain queries.
Example
Exercises for Students:
1. Create a
Single Field Index:
o
Create a collection named products and create an
index on the category field.
2. Create a
Compound Index:
o
Create a collection named employees and create a
compound index on department and salary.
3. View
Indexes:
o
After creating some indexes on the students collection,
list all the indexes using the getIndexes() method.
4. Drop an
Index:
o
Drop the index you created for the category field
in the products collection.
Conclusion:
Indexes are essential for
optimizing query performance in MongoDB. By understanding the different types
of indexes and how to create, view, and drop them, students will be able to
design efficient MongoDB databases. However, it’s important to use indexes
judiciously to ensure they improve performance without affecting write
operations too much.
Solution: Example Exercises for Students
1. Create
a Single Field Index:
Step 1:
Create a collection named products
First, we need to create a
collection called products. MongoDB automatically creates a collection when you
insert data.
javascript
CopyEdit
// Insert
sample data into the 'products' collection
db.products.insertMany([
{ name: "Product1", category: "Electronics",
price: 100 },
{ name: "Product2", category: "Electronics",
price: 150 },
{ name: "Product3", category: "Furniture",
price: 200 }
]);
Step 2:
Create an index on the category field
Now, we will create a
single-field index on the category field of the products collection.
javascript
CopyEdit
// Create
index on the 'category' field
db.products.createIndex({
category: 1 });
The 1 indicates an ascending
index. This index will improve query performance when searching for products by
category.
2. Create
a Compound Index:
Step 1:
Create a collection named employees
Insert some sample data into a
collection called employees.
javascript
CopyEdit
// Insert
sample data into the 'employees' collection
db.employees.insertMany([
{ name: "John", department: "HR",
salary: 4000 },
{ name: "Jane", department: "IT",
salary: 6000 },
{ name: "Mark", department: "HR",
salary: 4500 }
]);
Step 2:
Create a compound index on the department and salary fields
Now, we will create a compound
index on the department and salary fields.
javascript
CopyEdit
// Create
compound index on 'department' and 'salary' fields
db.employees.createIndex({
department: 1, salary: -1 });
The 1 indicates ascending order
for the department field, and the -1 indicates descending order for the salary
field.
3. View
Indexes:
Step 1:
Insert sample data into the students collection
Let's create a students
collection and add some documents to it.
javascript
CopyEdit
// Insert
sample data into the 'students' collection
db.students.insertMany([
{ name: "Alice", grade: "A",
age: 20 },
{ name: "Bob", grade: "B",
age: 22 },
{ name: "Charlie", grade: "A",
age: 21 }
]);
Step 2:
Create some indexes for the students collection
We will create a few indexes on
the name and age fields.
javascript
CopyEdit
// Create
an index on the 'name' field
db.students.createIndex({
name: 1 });
// Create
an index on the 'age' field
db.students.createIndex({
age: 1 });
Step 3:
View all indexes in the students collection
Now, let's view all the indexes
that exist on the students collection using the getIndexes() method.
javascript
CopyEdit
// View all
indexes in the 'students' collection
db.students.getIndexes();
This will return a list of all
indexes in the students collection, including the default _id index and any
custom indexes we've created.
4. Drop
an Index:
Step 1:
Drop the index created for the category field in the products collection
If we no longer need the index on
the category field, we can drop it using the dropIndex() method. First, let's
identify the name of the index created on the category field.
To find the index name, run:
javascript
CopyEdit
// View
all indexes in the 'products' collection
db.products.getIndexes();
After checking the output, the
name of the index should be something like "category_1". Now, let's
drop that index.
javascript
CopyEdit
// Drop
the index on the 'category' field
db.products.dropIndex("category_1");
This will remove the index we
created on the category field of the products collection.
Conclusion:
- We
have created a single-field index on the category field of the products
collection.
- We
have created a compound index on the department and salary fields
of the employees collection.
- We
have viewed the indexes of the students collection using the getIndexes()
method.
- We
have dropped the index on the category field in the products collection
using the dropIndex() method.
