MongoDB Remove Index - A quick demo of removing an index in MongoDB

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

The purpose of this article is to show you the simplest way to remove an index in MongoDB. We’ll first demo how to do in the MongoDB Shell because the syntax is almost exactly the same across the long list of drivers including NodeJS, PHP, Python. We will also show how to remove it using the drivers for NodeJS so you can see how similar it is.

Prerequisites

  • You should have MongoDB installed on your system.
  • You can follow along using the MongoDB Shell or with whatever driver you’re using.

db.collection.dropIndex() and db.collection.dropIndexes()

Removing an index in MongoDB is referred to as ‘Dropping’ an index in MongoDB. The functions typically used are these two:

  • db.collection.dropIndex()
  • db.collection.dropIndexes()

You’ll use db.collection.dropIndex() if you want to drop a single specific index and you’ll use db.collection.dropIndexes() if you want to drop all the indexes on a collection.

Demo db.collection.dropIndex()

Let’s jump into a quick demo by creating a super simple database, collection, and then removing an index. Let’s go:

First we’ll create a database grocerydb for a small grocery store:

1
2
> use grocerydb;
switched to db grocerydb

Then we create a collection for products: > db.createCollection("products");
{ "ok" : 1 }

Then we put some data in the collection: ` > db.collection.insert( [{


1
2
3
    "name" : "Soda",
    "quantity" : 10,
    "price" : 5.5

} {


1
2
3
    "name" : "Bread",
    "quantity" : 9,
    "price" : 2.5

} {


1
2
3
    "name" : "Milk",
    "quantity" : 4,
    "price" : 3.5

}] ) `

Let’s get a list of the indexes on the collection: ` db.products.getIndexes(); [


1
2
3
4
5
6
7
8
    {
            "v" : 2,
            "key" : {
                    "_id" : 1
            },
            "name" : "_id_",
            "ns" : "grocerydb.products"
    }

] `

Every collection has an index so even though we just created it, this collection has an index on the id.

Let’s create and index on the price and then remove it later. Let’s create it first: ` > db.products.createIndex( { price: 1 } ) {


1
2
3
4
    "createdCollectionAutomatically" : false,
    "numIndexesBefore" : 1,
    "numIndexesAfter" : 2,
    "ok" : 1

} `

Now let’s list the indices again so we can see the price index before we remove it: ` [


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    {
            "v" : 2,
            "key" : {
                    "_id" : 1
            },
            "name" : "_id_",
            "ns" : "grocerydb.products"
    },
    {
            "v" : 2,
            "key" : {
                    "price" : 1
            },
            "name" : "price_1",
            "ns" : "grocerydb.products"
    }

] `

We can see the name of our new price index is “price_” which we’ll need to remove it.

Now the moment of truth, let’s remove the price index by name: db.products.dropIndex( "price_1" );
{ "nIndexesWas" : 2, "ok" : 1 }

Now let’s list the indexes to verify it was removed: ` db.products.getIndexes(); [


1
2
3
4
5
6
7
8
    {
            "v" : 2,
            "key" : {
                    "_id" : 1
            },
            "name" : "_id_",
            "ns" : "grocerydb.products"
    }

] `

YES! There is now only the index on the id field but the price index was removed as expected.

Demo db.collection.dropIndexes()

Now let’s do a similar demo but we’ll add multiple indexes and then remove them using the dropIndexes() function.

We’ll start off where we left off with the grocerydb with a products collection with the three documents in it.

Let’s add two indexes one on the name and one on the price:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
> db.products.createIndex( { price: 1 } );
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}
> db.products.createIndex( { name: 1 } );
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 2,
        "numIndexesAfter" : 3,
        "ok" : 1
}

Let’s list our indexes so we can see the new indexes before we remove them:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
>db.products.getIndexes();
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "grocerydb.products"
        },
        {
                "v" : 2,
                "key" : {
                        "price" : 1
                },
                "name" : "price_1",
                "ns" : "grocerydb.products"
        },
        {
                "v" : 2,
                "key" : {
                        "name" : 1
                },
                "name" : "name_1",
                "ns" : "grocerydb.products"
        }
]

As you can see we have two new indexes. Now let’s remove both of them using the dropIndexes():

1
2
3
4
5
6
db.products.dropIndexes();
{
        "nIndexesWas" : 3,
        "msg" : "non-_id indexes dropped for collection",
        "ok" : 1
}

Let’s list our collections to verify that they were removed:

1
2
3
4
5
6
7
8
9
10
11
db.products.getIndexes();
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "grocerydb.products"
        }
]

IT WORKED! The two indexes we added were removed.

Note: We’re back to only having the single index on the id. Note that this index was created automatically on the collection and cannot be removed.

NodeJS Javascript Demo

The script to drop the “price_1” index in NodeJS using Javascript would be:

1
2
3
4
5
6
7
8
9
10
11
12
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("grocerydb");
  dbo.collection("products").dropIndex("price_1", function(err, delOK) {
    if (err) throw err;
    if (delOK) console.log("Collection deleted");
    db.close();
  });
});

Conclusion

We demonstrated how to remove an index or multiple indexes from a collection using the dropIndex and dropIndexes methods. We demo’d it in the MongoDB Shell and also showed what a script would look like in Javascript.

If you want to move to having your MongoDB data and the complexity of a production environment managed by experts, don’t hesitate to reach out to us at Object Rocket.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.