Managing Indexes in MongoDB

Introduction

Do you remember flipping through a textbook or cookbook looking for a certain topic or recipe? If the book had an index in the back, that was usually the first place to start. The index was alphabetized and anything could be found by searching for one main word. It was easier to find something using the index, rather flipping through the table of contents. Indexes in MongoDB are very similar to this analogy. They improve the performance of a query by storing key-value data that helps find fields without going through each document one by one.

Prerequisites

  • You should have MongoDB installed
  • It’s not required but it’s recommended that you have some previous shell experience with MongoDB.
  • You should have access to the MongoDB shell ( Execute mongo )

Index Basics

Before we dive into managing indexes and discussing how to optimize the size of your index, let’s start with a few basics in case you are just getting started with mongoDB.

Creating an Index

An index can be created with one field, or multiple fields in the collection. In the following example we have a database, called ‘cupcakes’ with a collection called frosting and we will create an index based on the frosting flavors:

> db.frosting.createIndex({ flavor: 1 })
{
    "createdCollectionAutomatically" : false,
    "numIndexesBefore" : 1,
    "numIndexesAfter" : 2,
    "ok" : 1
}

When an index is created, the values are going to be sorted. So just like the sorting methods, you have to pass a parameter of 1 or -1 to set the values in ascending or descending order. In the example above, we are going to have all the flavors sort in ascending order.

Finding an Index

To see your indexes within a collection, simply select the collection and run the getIndexes() method. This will list only the indexes within that collection. Note: ns means the namespace.

> db.frosting.getIndexes()
[
    {
        "v" : 2,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "cupcakes.frosting"
    },
    {
        "v" : 2,
        "key" : {
            "flavor" : 1
        },
        "name" : "flavor_1",
        "ns" : "cupcakes.frosting"
    },
    {
        "v" : 2,
        "key" : {
            "icing" : 1
        },
        "name" : "icing_1",
        "ns" : "cupcakes.frosting"
    }
]

Dropping an Index

Once you get to a point where you have too many indexes, you hit performance degredation. There are some situations where indexes can become a problem and you need to manage your index usage. MongoDB uses memory to keep the indexes accessible and you will see slowness with both writes and overall performance. Also if you have too many competing indexes MongoDB can select the wrong index for a query. Make it a practice to regularly evalutate your existing indexes. When you see that you might have some that are no longer needed, you can remove an index at any time using the dropindex() method.

It’s very simple to remove any inex you might have, but be sure and verify that you are dropping the right one. Here’s our example below:

> use cupcakes
switched to db cupcakes
> db.frosting.getIndexes()
[
    {
        "v" : 2,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "cupcakes.frosting"
    },
    {
        "v" : 2,
        "key" : {
            "flavor" : 1
        },
        "name" : "flavor_1",
        "ns" : "cupcakes.frosting"
    },
    {
        "v" : 2,
        "key" : {
            "icing" : 1
        },
        "name" : "icing_1",
        "ns" : "cupcakes.frosting"
    }
]
> db.frosting.dropIndex("flavor_1")
{ "nIndexesWas" : 3, "ok" : 1 }
>

Let’s quickly go over the response that was received from dropping the index:

  • nIndexesWas: in the example above, the value was 3. This indicates how many fields were in that index before it was dropped.
  • ok: if the value = 1, then the drop was successful.

Conclusion

Indexes help MongoDB to look for specific documents that match a criteria, instead of searching every document in the database using a collection scan. In this article, you learned to create a simple index, list all indexes, and drop an index. When we use indexes, we can search the documents in a collection faster and more efficiently. Be careful to watch the performance of your writes and ensure you don’t have too many indexes that will later cause a problem.

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.