In this MongoDB tutorial, we are going to cover what is “Create index” and how to create an index in MongoDB. We will also cover this with different operations and examples. These are the following topics that we are going to cover in this tutorial:
- What is create an index in MongoDB?
- Create index in MongoDB query
- Create index in MongoDB example
- Create multiple indexes in MongoDB
- Create index in ascending order in MongoDB
- Create index in descending order in MongoDB
- MongoDB create an index in a nested field
- Create index in MongoDB atlas
- Create index in MongoDB compass
- Create index in MongoDB using python
What is create an index in MongoDB?
In MongoDB, indexes are special data structures that, store a small part of the data set form that we can easily traverse.
If we don’t use indexes then MongoDB must have to scan every document of a collection to select those documents that match the query statement. This scan is highly ineffective and requires MongoDB to process a large volume of data. So to resolve this and for the time-saving purpose, we have to create the indexes in MongoDB.
The createIndex method is used for creating an index. It can be created on one field or multiple field values. MongoDB also provides some more methods as getIndexes, dropIndexes for finding the index and dropping all the indexes respectively.
Also, Read: MongoDB join two collections
Create index in MongoDB query
Indexes are very important in the MongoDB database. With the use of indexes, Performing the queries in MongoDB becomes more efficient.
The createIndex method is used to create the index in MongoDB. The index stores the value of a specific field or a set of fields. It also returns the sorted results by using the ordering in the index.
Syntax:
db.collection.createIndex()
The createIndex() method takes the following parameters:
Parameter | Type | Description |
---|---|---|
keys | documents | The document contains the field and value pairs. Here the field is the index key and the value is the type of index for that field. For an ascending index on a field specify a value of 1 and for descending index specifies a value of -1. |
options | documents | Optional, A document that contains a set of options that controls the creation of the index. |
commitQuorum | integer or string | Optional, The minimum number of data-bearing voting replica set members, including the primary, that must report a successful index build before the primary marks the indexes as ready. |
Options
The options documents contain a set of options that controls the creation of the index.
In the same document, we can specify the multiple index options. Consider the following operation:
db.collection.createIndex(
{
"a": 1
},
{
unique: true,
sparse: true,
expireAfterSeconds: 3600
}
)
Note that, If the specification of the option had been split into multiple documents like this: { unique: true }, { sparse: true, expireAfterSconds: 3600 } the index creation operation would have failed.
The following options are available for all index types except differently defined:
Parameter | Type | Description |
---|---|---|
background | boolean | Optional, Deprecated in MongoDB 4.2 background: true direct MongoDB to build the index in the background. |
unique | boolean | Optional, Create a unique index so that the collection will not accept insertion or update of documents where the index key value matches an existing value in the index. Specify, true to create a unique index. The default value is false. |
name | string | Optional, The name of the index is unspecified then MongoDB generates an index name by concatenating the names of the indexed fields. |
partialFilterExpression | document | Optional, the index only references documents that match the filter expression. |
sparse | boolean | Optional, If true then index references documents with the specified field. |
expireAfterSeconds | integer | Optional, Specifies a value in seconds, to control how long MongoDB retains documents in this collection. |
weight | documents | It denotes the importance of the field relative to the other indexed fields in terms of the score. |
These are some of the options that are used in the createIndex() method. And, some other options are also there that is provided by MongoDB as Collation, text Indexes, 2dsphare, 2d, geoHaystack, wildcard.
Read: Import CSV into MongoDB
Create index in MongoDB example
In this topic, we learn to create an index in MongoDB with the help of an example.
Example:
The following documents are inserted into the studentgrades collection:
db.studentgrades.insertMany([
{name: "Barry", subject: "Maths", score: 92},
{name: "Kent", subject: "Physics", score: 87},
{name: "Harry", subject: "Maths", score: 99, notes: "Exceptional Performance"},
{name: "Alex", subject: "Literature", score: 78},
{name: "Tom", subject: "History", score: 65, notes: "Adequate"}
])
While creating an index, you need to define the field to be indexed and the direction of the key 1 or -1 to indicate ascending or descending order respectively.
After inserting the documents into the collection, apply the createIndex() method on the documents:
db.studentgrades.createIndex({ "name": 1 })
Here, we created an index on the name field and specify the direction key 1 for ascending order.
By default, MongoDB creates the index name by concatenating the indexed key with the direction of each key using an underscore. For e.g. {name: 1} will be created as name_1 .
Execution:

After executing the command, the following output will be shown:
1. numIndexesBefore: It shows that how many indexes are there before the command is executed. Note that each collection has the _id field which also counts as a Field value to the index. As the _id index field is part of the collection when it is created so that the value of numIndexesBefore is 1.
2. numIndexesAfter: It shows that how many indexes are thereafter the command is executed. 2 indicates the number of Field values after the command was run.
3. The “ok: 1” output tells that the new index is added to the collection.
We successfully created the indexes for studentgrades collection and we can also check them by using the getIndexes method.
In the following topic, you will understand how to return all the indexes of a specific collection.
Finding indexes
We can find all the available indexes in a MongoDB collection by using the getIndexes method. This will return all the indexes of a specific collection.
Syntax:
db.<collection>.getIndexes()
Let’s view all the indexes in the studentgrades collection using the following command:
db.studentgrades.getIndexes()

The output contains the default _id index and the newly created index name_1.
Read: MongoDB group by multiple fields
Create multiple indexes in MongoDB
In MongoDB, we can also build multiple indexes at once. For creating the multiple indexes, we have to use createIndexes() and pass the multiple keys into an array.
Syntax:
db.collection.createIndexes()
The createIndexes() takes the following parameters:
Parameter | Type | Description |
---|---|---|
keyPatterns | document | The document contains the field and value pairs. Here the field is the index key and the value is the type of index for that field. For an ascending index on a field specify a value of 1 and for descending index specifies a value of -1. |
Options | document | Optional, A document that contains a set of options that controls the creation of the index. |
commitQuorum | integer or string | Optional, The minimum number of data-bearing voting replica set members, including the primary, that must report a successful index build before the primary marks the indexes as ready. |
Example:
In this example, we will learn to create multiple indexes at once in MongoDB.
The following documents were inserted into the car collection:
db.car.insertMany([
{"name": "Audi","color": "Red","cno": "H101","mfdcountry": "Germany","speed": 75 },
{"name": "Swift","color": "Black","cno": "H102","mfdcountry": "Italy","speed": 60 },
{"name": "Tesla","color": "Blue","cno": "H103","mfdcountry": "USA","speed": 70 },
{"name": "Polo","color": "White","cno": "H104","mfdcountry": "Japan","speed": 65 },
{"_id": 5,"name": "Volkswagen","color": "JetBlue","cno" : "H105","mfdcountry": "Rome","speed": 80 }
])
After successfully inserting the documents into the car collection. The following is the query for building multiple indexes at once
db.car.createIndexes([
{ "name": 1 },
{ "cno": 1 },
{ "speed": 1 }
])
Here, we created multiple indexes at once on the name, cno, and speed fields and specify the direction key 1 for ascending order.
Execution:

After executing the command, the following output will be shown:
1. numIndexesBefore: It shows that how many indexes are there before the command is executed. Note that each collection has the _id field which also counts as a Field value to the index. As the _id index field is part of the collection when it is created so that the value of numIndexesBefore is 1.
2. numIndexesAfter: It shows that how many indexes are thereafter the command is executed. 4 indicates the number of Field values after the command was run.
3. The “ok: 1” explains the new index is successfully added to the collection.
Now to get all the indexes with the help of the getIndexes() method:
db.car.getIndexes()

The output contains the default _id index and the newly created indexes name_1, con_1, and speed_1.
Read: MongoDB drop collection
Create index in ascending order in MongoDB
In MongoDB, we can create an ascending index on the field for a collection and this index helps in an ascending sort. The reason is using INDEX because it is a sorted data structure so the request will be performed faster.
Now, we create the index in ascending order in MongoDB and more understand with the help of an example.
Example:
The following documents were inserted into the Details collection
db.Details.insertMany(
[
{
First_Name: "Olivia",
Last_Name: "Thomas",
Date_Of_Birth: "1995-09-26",
e_mail: "Olivia_Thomas.123@gmail.com",
phone: "9000012345",
city: "United States of America"
},
{
First_Name: "Emma",
Last_Name: "Christopher",
Date_Of_Birth: "1990-02-16",
e_mail: "Emma_Christopher.123@gmail.com",
phone: "9000054321",
city: "Australia"
},
{
First_Name: "Fathima",
Last_Name: "Sheik",
Date_Of_Birth: "1990-02-16",
e_mail: "Fathima_Sheik.123@gmail.com",
phone: "9000054321",
city: "New Zealand"
}
]
)
After inserting the documents into the Details collection. Now, we will create the multiple indexes in ascending order by using the following query
db.Details.createIndexes([{ "First_name": 1}, {"Date_Of_Birth": 1 }])
Here we created multiple indexes in ascending order on First_name and Date_Of_Birth fields.

Now to get all the indexes with the help of the getIndexes() method:
db.Details.getIndexes()

Here, we successfully created the multiple indexes in ascending order.
Read: How to store images in MongoDB
Create index in descending order in MongoDB
We can create an index in descending order on the field for a collection and this index can support a descending sort. The reason behind using INDEX because, it is a sorted data structure, so the request will be executed faster.
Now, we create the index in descending order in MongoDB and more understand with the help of an example.
Example:
In this example, we use the same collection (Details) as we use above and create an index in descending order on the First_Name field.
db.Details.createIndex({ "First_Name": -1})
Execution in MongoDB Shell:

Now to get all the indexes with the help of the getIndexes() method:
db.Details.getIndexes()

We successfully created an index in descending order on the First_name field.
Read: MongoDB group by count
MongoDB create an index in a nested field
In MongoDB, you can also create an index in a nested field. The nested type is the object data type that allows arrays of objects to be indexed in a way that they can be queried independently from each other. You will more understand with the help of an example:
Example:
The following documents were inserted into the demo collection:
db.demo.insertMany([
{"UserDetails":
{"UserPersonalDetails":
{"UserFirstName":"John",
"UserLastName":"Smith"}
}
},
{"UserDetails":
{"UserPersonalDetails":
{"UserFirstName":"Chris",
"UserLastName":"Brown"}
}
},
{"UserDetails":
{"UserPersonalDetails":
{"UserFirstName":"David",
"UserLastName":"Miller"}
}
}
])
Output:

Now, we create an index by using the below code:
db.demo.createIndex({"UserDetails.UserPersonalDetails.UserFirstName":1})
Here, we write the nested field UserFirstName in the createIndex method to create an index.

We successfully created an index on the UserFirstName nested field.
Read: Import JSON and insert JSON into MongoDB
Create index in MongoDB atlas
We can create an index in the MongoDB atlas but we must have an Atlas cluster for creating an Atlas Search index. And, you must have at least one collection. Choose a configuration method. The MongoDB version must be 4.2 or higher.

We can use either the default index definition or define a custom definition for the index. The default index definition will work with any collection. We can also create a custom index in which specify the field of the index with a data type.
The index name is default but we can leave the default name and choose our own.
Note that, Index names must be unique within their namespace.
Now we will create an index in a collection using MongoDB atlas and to understand in detail you have to follow the below steps:
- Login to MongoDB atlas
- Go to the Atlas cluster overview page
- Click on Databases in the top-left corner of atlas to navigate to the Database Deployments page of our project
- Click the cluster name to view cluster details

- In cluster details, click on search tab
- Create an index for first index so click on Create Search Index or if it is subsequent indexes then click on Create Index

- Now select the Configuration Method and click Next

- Here, the Visual Editor doesn’t support so to edit the raw index, click on JSON Editor
- Enter the Index Name by default index name is default.
- Now the database and collection section, select the collection name

- For the use of Visual Editor click on Next.
- Now review the default Atlas Search index configuration settings.

- Click on the Create Search Index Button.
- Now a model window appeares and it says that ypur index is building. Click on the Close button.

- New created index appears on the Search tab.
- When the index is finished building then status field reads Active.

We successfully created an index in MongoDB.
Here, the Status column reads Active and the index is ready to use. If there is any problem or error while creating an index then queries against the index may return incomplete results.
Status | Description |
---|---|
Not Started | Building of index is not started in Atlas |
Initial Sync | Atlas Search does not serve queries |
Active | The index is ready to use |
Recovering | This state usually occurs when the current replication point is no longer available |
Failed | Atlas could not build the index |
Delete in Progress | In this Atlas is deleting the index from the cluster nodes. |
Read: How to check if MongoDB is installed
Create index in MongoDB compass
In MongoDB Compass, Indexes are a special data structure that improves query performance. The indexes store a part of a collection’s data in the easy-to-traverse form.
Now, we will create an index in MongoDB compass and more understand with the help of an example.
Example:
You need to follow the below step to create an index on a particular field in MongoDB compass.
- Open MongoDB Compass
- Now create a new database and collection, if you want to
- Here, Selecting an existing database and collection, myDB and data respectively

- Click on Indexes tab on the top of the window
- The Indexes tab tab list the existing indexes for a collection
For each index, Compass displays the following information:
Column | Description |
---|---|
Name and Definition | The name of the index and keys. |
Type | Regular, text, geospatial, or hashed index. |
Size | How large the index is. |
Usages | The number of times the index has been used |
Properties | Any special properties of the index. |

- Click on CREATE INDEX buttion
- Enter the name of the index to create or leave it blank MongoDB craete a default name for the index
- Add field to index
Specify an index key
- Select the field name from the dropdown list
- Specify a field if not exist in any document as index key then enter the field name in the input box.
- To create a compound index, click Add Another Field.
- Use the dropdown to the right of each field name to specify the index type ascending, descending, 2dsphare and text.
- Optional. Specify the index options
Compass supports the following index options:
Option | Description |
---|---|
Build index in background | MongoDB deployment remain available during the index build operation |
Create unique index | The indexed fields do not store duplicate values |
Create a TTL index | Delete documents automatically after a specified number of seconds |
Partial filter expression | Index only the documents which match the specified filter expression |
Use Custom Collation | Create a custom collation for the index using the options provided in Compass |
Wildcard Projection | Support unknown or arbitrary fields that match the specified projection in the index |
See the execution of execution in MongoDB compass:

- Now click on CREATE INDEX button.

We successfully created indexes in MongoDB Compass. The Indexes is used to improve the speed of search operations in the database because instead of searching the complete document, the search is conducted on the indexes that hold only a few fields.
Read: MongoDB sort by date
Create index in MongoDB using python
When we create an index in MongoDB collection, query performance is improved because it stores the information in such a way that traversing becomes easier and efficient.
In this topic, we learn to create an index in MongoDB by using python. In python, we use the following syntax for creating an index
create_index([str1, direction], [str1, direction]……., optional)
Parameters are:
- str: We use string for naming index. We can also create multiple indexes.
- direction: It can be one or many direction. Like- descending, ascending, hashed, geosphere, geohaystack, geo2d or text.
Now, we will discuss some of the examples that will help you create an index in MongoDB using Python.
Example 1:
In this example, we create an index on the example collection of the myDB database with the help of Python.
from pymongo import MongoClient
# Create a pymongo client
client = MongoClient('localhost', 27017)
# database instance
db = client['myDB']
# collection instance
doc = db['example']
# Creating a single field index
res = doc.create_index("index_created")
print(res)
Here, we use the pymongo library for using MongoDB in python. and also use the MongoClient class of the pymongo library for making the connection. After that define database and collection. the create_index() function is used for creating an index in python.
See the execution of the above code:

Output:
After executing the code it shows the following output:
index_created_1
Now, We successfully created the index using python.
Note that, we don’t specify the direction while creating the index so by default it takes as in ascending order (1).
Example 2:
In this example, we create an index in descending order in the example collection of myDB database and using python
from pymongo import MongoClient
# Create a pymongo client
client = MongoClient('localhost', 27017)
# database instance
db = client['myDB']
# collection instance
doc = db['example']
# Creating a single field index in descending order
res = doc.create_index([ ("index_descending", -1) ])
print(res)
Here, we use the pymongo library for using MongoDB in python. and also use the MongoClient class of the pymongo library for making the connection. After that define database and collection.
The create_index() function is used for creating an index in python. And, also specify the parameter string (index name) index_descending and direction -1 for descending order.
Now, see the execution of the above code:

Output:
After executing the code it shows the following output:
index_descending_-1
Now, We successfully created the index in descending direction using python.
You may also like to read the following topics.
- Create tables in MongoDB
- Pros and cons of MongoDB
- MongoDB backup and restore
- How to create new database in MongoDB
In this tutorial, you have learned about “create an index in MongoDB” with different operations and examples. And we have also covered the following list of topics:
- What is create an index in MongoDB?
- Create index in MongoDB query
- Create index in MongoDB example
- Create multiple indexes in MongoDB
- Create index in ascending order in MongoDB
- Create index in descending order in MongoDB
- MongoDB create an index in a nested field
- Create index in MongoDB atlas
- Create index in MongoDB compass
- Create index in MongoDB using python
I am Bijay having more than 15 years of experience in the Software Industry. During this time, I have worked on MariaDB and used it in a lot of projects. Most of our readers are from the United States, Canada, United Kingdom, Australia, New Zealand, etc.
Want to learn MariaDB? Check out all the articles and tutorials that I wrote on MariaDB. Also, I am a Microsoft MVP.