Learning MongoDB

0% completed

Previous
Next
Drop an Index

Indexes are essential for optimizing query performance in MongoDB, but there are times when you may need to remove them. This could be due to changes in application requirements, the need to reclaim storage space, or to simplify index management. Dropping indexes that are no longer needed can help maintain optimal database performance and reduce overhead.

Syntax

To drop an index in MongoDB, you use the dropIndex() method. The basic syntax for dropping an index is:

db.collection.dropIndex(<index>)

Parameters

  • index: This can either be the name of the index (as a string) or an object describing the index key pattern.

Example Setup

First, let's insert some documents into the employees collection and create a few indexes:

db.employees.insertMany([ { name: "John Doe", age: 29, department: "HR" }, { name: "Jane Smith", age: 34, department: "Finance" }, { name: "Emily Davis", age: 42, department: "IT" }, { name: "Michael Brown", age: 36, department: "Marketing" }, { name: "Sarah Wilson", age: 30, department: "Sales" } ]) db.employees.createIndex({ name: 1 }, { unique: true, name: "uniqueNameIndex" }) db.employees.createIndex({ department: 1, age: -1 }, { name: "deptAgeIndex" })

Example 1: Dropping an Index by Name

Drop the index named uniqueNameIndex from the employees collection.

Command:

db.employees.dropIndex("uniqueNameIndex")

Explanation:

  • db.employees.dropIndex("uniqueNameIndex"): This command drops the index with the name uniqueNameIndex from the employees collection.

Example 2: Dropping an Index by Key Pattern

Drop the index on the department and age fields from the employees collection.

Command:

db.employees.dropIndex({ department: 1, age: -1 })

Explanation:

  • db.employees.dropIndex({ department: 1, age: -1 }): This command drops the index on the department field in ascending order and the age field in descending order from the employees collection.

Example 3: Dropping All Indexes

Drop all indexes on the employees collection except for the default _id index.

Command:

db.employees.dropIndexes()

Explanation:

  • db.employees.dropIndexes(): This command drops all indexes on the employees collection except for the default _id index.

Dropping allows you to remove unnecessary indexes, reclaim storage space, and optimize write performance. By understanding the syntax and use cases for the dropIndex() method, you can effectively manage your indexes and maintain optimal database performance.

.....

.....

.....

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