MongoDB dropIndex()

There are several ways to drop an index in MongoDB, one of which is to use the dropIndex() method.

It’s pretty simple to use – just pass the name of the index or its definition/specification document. If it’s a text index, you can only specify the index name.

Example Indexes

Suppose we have a collection called bars. We can use getIndexes() to see what indexes it has:

db.bars.getIndexes()

Result:

[
	{
		"v" : 2,
		"key" : {
			"_id" : 1
		},
		"name" : "_id_"
	},
	{
		"v" : 2,
		"key" : {
			"location" : "2dsphere"
		},
		"name" : "location_2dsphere",
		"2dsphereIndexVersion" : 3
	},
	{
		"v" : 2,
		"key" : {
			"name" : 1
		},
		"name" : "name_1",
		"hidden" : true
	}
]

We can see that there are three indexes on the bars collection.

  • The first index is on the _id field. MongoDB creates a unique index on the _id field during the creation of a collection. You cannot drop this index.
  • The second index is a 2dsphere index on the location field.
  • The third index is on the name field. In this case, it happens to be a hidden index (it’s got "hidden" : true in its specification).

Drop an Index by Name

Here’s an example of dropping an index by passing its name to the dropIndex() method:

db.bars.dropIndex("location_2dsphere")

Output:

{ "nIndexesWas" : 3, "ok" : 1 }

This tells us that the index was dropped successfully.

Drop an Index by its Specification

Here’s an example of dropping an index by passing its specification document to the dropIndex() method:

db.bars.dropIndex( { "name" : 1 } )

Output:

{ "nIndexesWas" : 2, "ok" : 1 }

We can see that this index was also dropped.

You’ll recall that this is the index that was hidden. You can drop hidden indexes without a problem (you don’t need to unhide them before you drop them).

Check the Results

Let’s run getIndexes() again to see the results:

db.bars.getIndexes()

Result:

[ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_" } ]

This time there’s only one index – the default _id index.

The dropIndex() method is a wrapper around the dropIndexes command.

MongoDB Documentation

See the MongoDB documentation for more information on the dropIndex() method.