Learning MongoDB

0% completed

Previous
Next
Create an Index

In MongoDB, an index is a data structure that improves the speed of data retrieval operations on a collection. Indexes are crucial for efficient querying and can significantly enhance the performance of read operations. Without indexes, MongoDB must perform a collection scan, which examines every document in a collection to select those that match the query statement. This can be very slow for large datasets.

Indexes support the efficient execution of queries by providing quick access to documents. They store a portion of the data set in a structure that is easy to traverse, which reduces the number of documents that MongoDB needs to scan to fulfill a query.

Syntax for Creating an Index

To create an index in MongoDB, you use the createIndex() method. The basic syntax for creating an index is:

db.collection.createIndex( { <field1>: <type1>, <field2>: <type2>, ... }, { <option1>: <value1>, <option2>: <value2>, ... } )
  • field1, field2, ... - The fields to be indexed.
  • type1, type2, ... - The type of index for each field. Use 1 for ascending order or -1 for descending order.
  • option1, option2, ... - Optional parameters to customize the index behavior.

Options

  • background: If true, the index is created in the background so that it does not block other database operations. Default is false.
  • unique: If true, the index enforces a uniqueness constraint on the indexed field(s). Default is false.
  • name: Specifies a name for the index. If not specified, MongoDB generates a name.
  • sparse: If true, the index only includes documents that contain the indexed field. Default is false.
  • expireAfterSeconds: Specifies a TTL (Time To Live) for the documents in the collection. The value is the number of seconds after which the documents expire.
  • partialFilterExpression: Specifies a filter for creating a partial index.
  • collation: Specifies the collation to use for the index.

Example Setup

First, let's insert some documents into the products collection to work with:

db.products.insertMany([ { name: "Apple", category: "Fruit", price: 1.2 }, { name: "Carrot", category: "Vegetable", price: 0.8 }, { name: "Banana", category: "Fruit", price: 1.1 }, { name: "Broccoli", category: "Vegetable", price: 1.5 }, { name: "Grapes", category: "Fruit", price: 2.0 } ])

Example 1: Creating a Single Field Index

Create an index on the name field in ascending order.

db.products.createIndex({ name: 1 })

Explanation:

  • db.products.createIndex({ name: 1 }): This command creates an index on the name field in ascending order. This index will speed up queries that filter or sort by the name field.

Example 2: Creating an Index with Options

Create a unique index on the name field and specify a name for the index.

db.products.createIndex( { name: 1 }, { unique: true, name: "uniqueNameIndex" } )

Explanation:

  • db.products.createIndex({ name: 1 }, { unique: true, name: "uniqueNameIndex" }): This command creates a unique index on the name field. The index enforces the uniqueness of the name field and is named "uniqueNameIndex".

Example 3: Creating a Compound Index

Create a compound index on the category and price fields.

db.products.createIndex({ category: 1, price: -1 })

Explanation:

  • db.products.createIndex({ category: 1, price: -1 }): This command creates a compound index on the category field in ascending order and the price field in descending order. This index will speed up queries that filter or sort by both category and price.

Use Cases

  1. Speeding Up Queries: Indexes are essential for improving query performance. For example, if you frequently query the products collection by name, an index on the name field can significantly speed up these queries.
  2. Supporting Sorting: Indexes can also be used to support sorting operations. For example, if you often sort the products collection by price, an index on the price field can make these sorts much faster.
  3. Ensuring Uniqueness: Indexes can enforce unique constraints. For example, creating a unique index on the name field ensures that each product has a unique name.
  4. Partial Indexes: Useful for indexing a subset of documents, improving performance by indexing only relevant documents.

Creating indexes in MongoDB is a fundamental technique to enhance query performance and ensure efficient data retrieval. By understanding how to create single field and compound indexes, and utilizing optional parameters to customize index behavior, you can optimize your database operations and improve the responsiveness of your applications.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next