w3resource

MongoDB: db.collection.dropIndex() method

db.collection.dropIndex

The db.collection.dropIndex() method is used to removes a specified index on a collection.

Note: You cannot drop the default index on the _id field.

Syntax:

db.collection.dropIndex(index)

Parameter:

Name Description Required /
Optional
Type
index Specifies the index to drop. You can specify the index either by the index name or by the index specification document.
To drop a text index, specify the index name.
Required string or document

Example: MongoDB: db.collection.dropIndex() method

Here we have created a duplicate of restaurants collection restaurants1 and the following indexes we have created on restaurants1 collection.

> db.restaurants1.getIndexes();
[
        {
                "v" : 1,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "test.restaurants1"
        },
        {
                "v" : 1,
                "key" : {
                        "cuisine" : 1
                },
                "name" : "cuisine_1",
                "ns" : "test.restaurants1"
        },
        {
                "v" : 1,
                "key" : {
                        "cuisine" : 1,
                        "address.zipcode" : -1
                },
                "name" : "cuisine_1_address.zipcode_-1",
                "ns" : "test.restaurants1"
        }
]

The single field index on the fieldcuisinehas the user-specified name ofcuisine_1and the index specification document of{"cuisine":1}.

Now, the following statement will drop the index cuisine_1 index.


db.restaurants1.dropIndex( "cuisine_1" );

or 

db.restaurants1.dropIndex( { "cuisine": 1 } );

Here is the output

> db.restaurants1.dropIndex( "cuisine_1" );
{ "nIndexesWas" : 3, "ok" : 1 }

or 

> db.restaurants1.dropIndex( { "cuisine": 1 } );
{ "nIndexesWas" : 3, "ok" : 1 }

Now, lists the indexes again.


> db.restaurants1.getIndexes();
[
        {
                "v" : 1,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "test.restaurants1"
        },
        {
                "v" : 1,
                "key" : {
                        "cuisine" : 1,
                        "address.zipcode" : -1
                },
                "name" : "cuisine_1_address.zipcode_-1",
                "ns" : "test.restaurants1"
        }
]

Retrieve the restaurants data from here

Previous: db.collection.drop() method
Next: db.collection.dropIndexes() method



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/mongodb/shell-methods/collection/db-collection-dropIndex.php