Create MongoDB Indexes

MongoDBMongoDBBeginner
Practice Now

Introduction

In this lab, you will learn the basic concepts and techniques of creating indexes in MongoDB. The lab covers the following steps: creating a single field index, building a compound index, setting a unique index, checking index usage, and viewing the index list. These indexing techniques can significantly improve the performance of your MongoDB queries by optimizing data retrieval. The lab provides hands-on examples and step-by-step instructions to help you understand and apply these indexing concepts effectively.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL mongodb(("`MongoDB`")) -.-> mongodb/BasicOperationsGroup(["`Basic Operations`"]) mongodb(("`MongoDB`")) -.-> mongodb/QueryOperationsGroup(["`Query Operations`"]) mongodb(("`MongoDB`")) -.-> mongodb/IndexingGroup(["`Indexing`"]) mongodb(("`MongoDB`")) -.-> mongodb/RelationshipsGroup(["`Relationships`"]) mongodb/BasicOperationsGroup -.-> mongodb/insert_document("`Insert Document`") mongodb/QueryOperationsGroup -.-> mongodb/find_documents("`Find Documents`") mongodb/QueryOperationsGroup -.-> mongodb/query_with_conditions("`Query with Conditions`") mongodb/IndexingGroup -.-> mongodb/create_index("`Create Index`") mongodb/IndexingGroup -.-> mongodb/build_compound_index("`Build Compound Index`") mongodb/RelationshipsGroup -.-> mongodb/create_document_references("`Create Document References`") subgraph Lab Skills mongodb/insert_document -.-> lab-422078{{"`Create MongoDB Indexes`"}} mongodb/find_documents -.-> lab-422078{{"`Create MongoDB Indexes`"}} mongodb/query_with_conditions -.-> lab-422078{{"`Create MongoDB Indexes`"}} mongodb/create_index -.-> lab-422078{{"`Create MongoDB Indexes`"}} mongodb/build_compound_index -.-> lab-422078{{"`Create MongoDB Indexes`"}} mongodb/create_document_references -.-> lab-422078{{"`Create MongoDB Indexes`"}} end

Create Single Field Index

In this step, you'll learn how to create a single field index in MongoDB, which can significantly improve query performance by allowing faster data retrieval.

First, let's start the MongoDB shell and prepare our environment:

mongosh

Once you're in the MongoDB shell, let's create a database and a collection with some sample data:

use indexlab
db.users.insertMany([
    { name: "Alice", age: 28, email: "[email protected]" },
    { name: "Bob", age: 35, email: "[email protected]" },
    { name: "Charlie", age: 42, email: "[email protected]" }
])

Now, let's create a single field index on the "age" field:

db.users.createIndex({ age: 1 });

The 1 indicates an ascending index. If you want a descending index, you would use -1.

To verify the index creation, use the following command:

db.users.getIndexes();

Example output:

[
  { v: 2, key: { _id: 1 }, name: '_id_' },
  { v: 2, key: { age: 1 }, name: 'age_1' }
]

Let's check the performance improvement by running a query with and without the index:

db.users.find({ age: 35 }).explain("executionStats");

The explain() method will show you details about how the query is executed, including whether an index was used.

Build Compound Index

In this step, you'll learn how to create a compound index in MongoDB, which allows indexing multiple fields to optimize complex queries.

Let's continue using the database and collection from the previous step:

use indexlab

A compound index is an index on multiple fields. We'll create an index that combines the "name" and "age" fields to improve query performance for searches that involve both fields:

db.users.createIndex({ name: 1, age: 1 });

This creates an index where documents are first sorted by name in ascending order, and then by age in ascending order.

Let's add some more documents to demonstrate the compound index:

db.users.insertMany([
  { name: "David", age: 28, email: "[email protected]" },
  { name: "Eve", age: 28, email: "[email protected]" },
  { name: "Frank", age: 35, email: "[email protected]" }
]);

Now, let's verify the compound index:

db.users.getIndexes();

Example output:

[
  { v: 2, key: { _id: 1 }, name: '_id_' },
  { v: 2, key: { age: 1 }, name: 'age_1' },
  { v: 2, key: { name: 1, age: 1 }, name: 'name_1_age_1' }
]

Let's run a query that can benefit from this compound index:

db.users.find({ name: "David", age: 28 }).explain("executionStats");

This query will use the compound index we just created, which can significantly improve query performance.

Set Unique Index

In this step, you'll learn how to create a unique index in MongoDB, which prevents duplicate values in a specific field or combination of fields.

Let's continue using our existing database:

use indexlab

A unique index ensures that no two documents can have the same value for the indexed field(s). We'll create a unique index on the "email" field to prevent duplicate email addresses:

db.users.createIndex({ email: 1 }, { unique: true });

Now, let's try to insert documents with duplicate email addresses:

// This will succeed
db.users.insertOne({
  name: "Grace",
  age: 29,
  email: "[email protected]"
});

// This will fail due to the unique index
try {
  db.users.insertOne({
    name: "Henry",
    age: 30,
    email: "[email protected]"
  });
} catch (e) {
  print("Duplicate email error:", e.message);
}

Let's verify the unique index:

db.users.getIndexes();

Example output:

[
  { v: 2, key: { _id: 1 }, name: '_id_' },
  { v: 2, key: { age: 1 }, name: 'age_1' },
  { v: 2, key: { name: 1, age: 1 }, name: 'name_1_age_1' },
  { v: 2, key: { email: 1 }, name: 'email_1', unique: true }
]

You can also create a unique index on multiple fields. This means the combination of those fields must be unique:

db.users.createIndex({ name: 1, age: 1 }, { unique: true });

This allows different users to have the same name or same age, but not the exact same name and age combination.

Check Index Usage

In this step, you'll learn how to analyze and understand index usage in MongoDB using the explain() method to optimize query performance.

Let's continue using our existing database:

use indexlab

First, let's run a query without specifying an index and examine its performance:

db.users.find({ name: "Alice", age: 28 }).explain("executionStats");

Key things to look for in the output:

  • winningPlan.stage: Look for "COLLSCAN" (collection scan), which means it's scanning all documents
  • totalDocsExamined: Number of documents scanned
  • executionTimeMillis: Time taken to execute the query

Now, let's run a query that uses our previously created compound index:

db.users
  .find({ name: "Alice", age: 28 })
  .hint({ name: 1, age: 1 })
  .explain("executionStats");

The .hint() method forces MongoDB to use a specific index. Compare this output with the previous one:

  • winningPlan.stage should now show "FETCH" and "IXSCAN"
  • totalDocsExamined should be much lower
  • executionTimeMillis should be significantly reduced

Let's create a more complex query to demonstrate index usage:

db.users.createIndex({ email: 1, age: 1 });

db.users
  .find({
    email: { $gt: "[email protected]" },
    age: { $gte: 30 }
  })
  .explain("executionStats");

This query uses a range condition on both email and age, which can benefit from a compound index.

Example output will show:

  • How the index is used
  • Performance improvements
  • Detailed query execution statistics

View Index List

In this final step, you'll learn how to view and manage the list of indexes in your MongoDB database, which is crucial for understanding and optimizing database performance.

Let's continue using our existing database:

use indexlab

To view all indexes in the current database, use the getIndexes() method:

db.users.getIndexes();

Example output will look like:

[
  { v: 2, key: { _id: 1 }, name: '_id_' },
  { v: 2, key: { age: 1 }, name: 'age_1' },
  { v: 2, key: { name: 1, age: 1 }, name: 'name_1_age_1' },
  { v: 2, key: { email: 1 }, name: 'email_1', unique: true },
  { v: 2, key: { email: 1, age: 1 }, name: 'email_1_age_1' }
]

Let's get more detailed information about the indexes:

db.users.getIndexes().forEach(function (index) {
  print("Index Name: " + index.name);
  print("Index Key: " + JSON.stringify(index.key));
  print("Unique: " + (index.unique ? "Yes" : "No"));
  print("---");
});

To drop an index, use the dropIndex() method. Let's remove the index on email:

db.users.dropIndex("email_1");

Verify the index has been removed:

db.users.getIndexes();

You can also drop multiple indexes at once:

// Drop multiple specific indexes
db.users.dropIndexes(["name_1_age_1", "email_1_age_1"]);

To drop all user-created indexes (keeping the default _id index):

db.users.dropIndexes();

Summary

In this lab, you learned how to create single field indexes in MongoDB to improve query performance by allowing faster data retrieval. You also explored building compound indexes, which can optimize complex queries by indexing multiple fields. Additionally, you learned how to set unique indexes to ensure data uniqueness, check index usage, and view the list of indexes for a collection.

The key takeaways from this lab include understanding the importance of indexing, the different types of indexes (single field and compound), and how to manage and monitor indexes in a MongoDB database. These techniques can significantly enhance the efficiency and performance of your MongoDB applications.

Other MongoDB Tutorials you may like