MongoDB Indexing - Create, Find and Drop Index

In this post, we will see how to create, find and drop indexes in MongoDB.
Indexes support the efficient execution of queries in MongoDB. Without indexes, MongoDB must perform a collection scan, i.e. scan every document in a collection, to select those documents that match the query statement. If an appropriate index exists for a query, MongoDB can use the index to limit the number of documents it must inspect.
In this post, you will learn –
  • How to Create Indexes: createIndex()
  • How to Find Indexes: getIndexes()
  • How to Drop Indexes: dropIndex()

1. How to Create Indexes: createIndex()

Creating an Index in MongoDB is done by using the "createIndex()" method.

Syntax:

db.collection_name.createIndex({field_name: 1 or -1})
  • The value 1 is for ascending order and -1 is for descending order.
  • The db.collection.createIndex() method only creates an index if an index of the same specification does not already exist.
  • MongoDB indexes use a B-tree data structure.

Example

Let's say we want to create the index on title field of a post in ascending order:
> db.posts.createIndex({title: 1});
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}
Complete example:
> db.posts.createIndex({title: 1});
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}
> db.posts.find().pretty();
{
        "_id" : ObjectId("5e184a067695f4d696a0598d"),
        "title" : "MongoDB Overview",
        "description" : "MongoDB is no sql database",
        "by" : "Java Guides",
        "url" : "https://javaguides.net",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 100
}
{
        "_id" : ObjectId("5e184a067695f4d696a0598e"),
        "title" : "NoSQL Database",
        "description" : "NoSQL database doesn't have tables",
        "by" : "Java Guides",
        "url" : "https://javaguides.net",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 20,
        "comments" : [
                {
                        "user" : "user1",
                        "message" : "My first comment",
                        "dateCreated" : ISODate("2013-12-10T09:35:00Z"),
                        "like" : 0
                }
        ]
}
{
        "_id" : ObjectId("5e18544a7695f4d696a0598f"),
        "title" : "MongoDB CRUD Operations",
        "description" : "MongoDB CRUD Operations",
        "by" : "Java Guides",
        "url" : "https://javaguides.net",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 20,
        "comments" : [
                {
                        "user" : "user1",
                        "message" : "My first comment",
                        "dateCreated" : ISODate("2013-12-10T09:35:00Z"),
                        "like" : 0
                }
        ]
}

How to Find Indexes: getIndexes()

Finding an Index in MongoDB is done by using the "getIndexes()" method.

Syntax

db.collection_name.getIndexes()

Example

> db.posts.getIndexes();
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "mydb.posts"
        },
        {
                "v" : 2,
                "key" : {
                        "title" : 1
                },
                "name" : "title_1",
                "ns" : "mydb.posts"
        }
]
The output shows that we have two indexes in this collection. The default index created on _id and the index that we have created on title field.

How to Drop Indexes: dropIndex()

Removing an Index in MongoDB is done by using the "dropIndex()" method.
We can either drop a particular index or all the indexes.

Dropping a specific index

db.collection_name.dropIndex({index_name: 1})
Let's drop the index that we have created on the title field in the collection posts. The command for this:
> db.posts.dropIndex({title: 1});
{ "nIndexesWas" : 2, "ok" : 1 }
nIndexesWas: It shows how many indexes were there before this command got executed ok: 1: This means the command is executed successfully.

Dropping all the indexes:

To drop all the indexes of a collection, we use dropIndexes() method.
Syntax of dropIndexs() method:
db.collection_name.dropIndexes()
Let's drop all the indexes of posts collection.
> db.posts.dropIndexes();
{
        "nIndexesWas" : 1,
        "msg" : "non-_id indexes dropped for collection",
        "ok" : 1
}

Summary

The below diagram shows the summary of all the commands used in this post:

Comments