Skip to content
Related Articles

Related Articles

Improve Article

MongoDB – dropIndex() Method

  • Last Updated : 08 Feb, 2021

The dropIndex() method drops or delete the specified index from the given collection. It takes only one parameter which is the index, that we want to drop and it is optional. To find the index name or the index specification document for the dropIndex() method, use getIndexes() method. 

  • Using this method you are not allowed to remove the default index of the _id field.
  • You can also drop the hidden indexes. 
  • Starting from MongoDB 4.4, in this method, if the specified index is still being built, then this method will abort the building process of the specified index.

Note: Starting from MongoDB 4.2, you are not allowed to remove all the non- _id indexes using db.Collection_Name.dropIndex(“*”). If you want to do that then use db.Collection_Name.dropIndexes() method.

Syntax:

db.Collection_Name.dropIndex(index : <document/string>)

Optional Parameters:



  • index: The type of this parameter is string or document. It specifies the index that we want to drop. We can specify the index either by the index name or by the index specification document. 

Return:

This method returns a document that contains nIndexesWas and Ok fields with their values.

Example: 

In the following examples, we are working with:

Database: gfg

Collection: student

Document: Three documents contains name and language that students use in coding



First of all we created an index on the name field using createIndex() method:

db.student.createIndex({name:2})

Now we want to see the index name, using getIndex() so we can drop that index:

db.student.getIndexes()

  • Drop the index with the name: name_1: 
db.student.dropIndex("name_1")

Here, we are going to drop the name: name_1 index using dropIndex() method. In this method, we are using the parameter as a string:

  • Drop the index with the name: 2:
db.student.dropIndex({name:2})

Here, we are going to drop the name: 2 index using dropIndex() method. In this method, we are using the parameter as a document:

My Personal Notes arrow_drop_up
Recommended Articles
Page :