Create index in MongoDB

In this MongoDB tutorial, we are going to cover how to create an index in MongoDB, including different methods, best practices, and practical examples.

Create index in MongoDB

What is an index in MongoDB?

In MongoDB, indexes are special data structures that store a small part of the data set from which we can easily traverse.

If we don’t use indexes, MongoDB must scan every document in a collection to select those that match the query statement. This scan is highly ineffective and requires MongoDB to process a large volume of data. To resolve this and save time, we need to create the indexes in MongoDB.

The createIndex method is used for creating an index. It can be made from a single field or multiple field values. MongoDB also provides additional methods, such as getIndexes and dropIndexes, for finding and dropping all indexes, respectively.

Also, read: MongoDB join two collections

Method 1: Using the createIndex() method

Indexes are significant 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:

ParameterTypeDescription
keysdocumentsThe 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 a descending index, specify a value of -1.
optionsdocumentsOptional: A document that contains a set of options that controls the creation of the index.
commitQuoruminteger or stringOptional: 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 control the creation of the index.

In the same document, we can specify 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, expireAfterSeconds: 3600 }, the index creation operation would have failed.

The following options are available for all index types except those defined differently:

ParameterTypeDescription
backgroundbooleanOptional, Deprecated in MongoDB 4.2
background: true, direct MongoDB to build the index in the background.
uniquebooleanOptional: 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.
namestringOptional: The name of the index is unspecified, then MongoDB generates an index name by concatenating the names of the indexed fields.
partialFilterExpressiondocumentOptional: the index only references documents that match the filter expression.
sparsebooleanOptional: If true, then index references documents with the specified field.
expireAfterSecondsintegerOptional: Specifies a value in seconds to control how long MongoDB retains documents in this collection.
weightdocumentsIt 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. Additionally, MongoDB offers several other options, including Collationtext Indexes2dsphere2dgeoHaystack, and wildcard.

Read: Import CSV into MongoDB 

Example 1: Creating a basic Index

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 student grades 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 specified 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:

Create index in MongoDB

After executing the command, the following output will be shown:

1. numIndexesBefore: It shows 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. When the collection is created, the _ id index field has a value of 1 for numIndexesBefore.

2. numIndexesAfter: It shows 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 the 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 indices 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()
Create index in MongoDB query

The output contains the default _id index and the newly created index name_1 as shown in the screenshot above.

Read: MongoDB group by multiple fields

Example 2: Creating multiple indexes in MongoDB

In MongoDB, we can also build multiple indexes at once. To create multiple indexes, we use createIndexes() and pass the various keys into an array.

Syntax:
db.collection.createIndexes()

The createIndexes() takes the following parameters:

ParameterTypeDescription
keyPatternsdocumentThe 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 a descending index, specify a value of -1.
OptionsdocumentOptional: A document that contains a set of options that controls the creation of the index.
commitQuoruminteger or stringOptional: 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 }
])

We created multiple indexes simultaneously on the name, cno, and speed fields, specifying direction key 1 for ascending order.

Execution:

Create multiple indexes in MongoDB

After executing the command, the following output will be shown:

1. numIndexesBefore: It shows 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 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 that the new index has been successfully added to the collection.

Now, to get all the indexes with the help of the getIndexes() method:

db.car.getIndexes()
Create multiple indexes in MongoDB example

The output contains the default _id index and the newly created indexes name_1, con_1, and speed_1 as shown in the above screenshot.

Read: MongoDB drop collection

Example 3: Creating an index in ascending order

In MongoDB, we can create an ascending index on a field for a collection, which helps with an ascending sort. The reason is that INDEX is used because it is a sorted data structure, which allows the request to be performed faster.

Now, we create the index in ascending order in MongoDB and gain a better understanding 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 multiple indexes in ascending order by using the following query

db.Details.createIndexes([{ "First_name": 1}, {"Date_Of_Birth": 1 }])

Here, we created various indexes in ascending order on the First_name and Date_Of_Birth fields.

how to create index in mongodb

Now, to get all the indexes with the help of the getIndexes() method:

db.Details.getIndexes()

After executing the above query, I got the expected output as shown in the screenshot below.

create index in mongodb example

Here, we successfully created multiple indexes in ascending order.

Read: How to store images in MongoDB

Example 4: Creating an index in descending order

We can create an index in descending order on the field for a collection, and this index can support a descending sort. The reason for using INDEX is that it is a sorted data structure, so the request will be executed faster.

Now, we create the index in descending order in MongoDB and gain a deeper understanding with the help of an example.

Example:

In this example, we use the same collection (Details) as we used above and create an index in descending order on the First_Name field.

db.Details.createIndex({ "First_Name": -1})

Execution in MongoDB Shell:

which is the method used to create index in mongodb

Now, to get all the indexes with the help of the getIndexes() method:

db.Details.getIndexes()

After executing the above query, I got the expected output as shown in the screenshot below.

how to create index in mongodb collection

We successfully created an index in descending order on the First_name field.

Read: MongoDB group by count

Example 4: Creating 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 understand better 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:

which of the following method is used to create index in mongodb

Now, we create an index by using the code below:

db.demo.createIndex({"UserDetails.UserPersonalDetails.UserFirstName":1})

Here, we write the nested field UserFirstName in the createIndex method to create an index.

how to create index in mongodb using spring boot

We successfully created an index on the UserFirstName nested field.

Read: Import JSON and insert JSON into MongoDB

Example 5: Creating an index in MongoDB Atlas

We can create an index in the MongoDB Atlas, but we must have an Atlas cluster to create 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.

Create index in MongoDB atlas

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, specifying the field and its data type.

The index name is default, but we can either leave it as is or 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 steps below:

  • Log in 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.
how to create index in mongodb atlas
  • In cluster details, click on the search tab.
  • To create an index, click on Create Search Index for the first index. For subsequent indexes, click on Create Index.
create unique index mongodb atlas
  • Now select the Configuration Method and click Next
create index mongodb atlas
  • Here, the Visual Editor doesn’t support editing the raw index, so click on JSON Editor
  • Enter the Index Name. The default index name is default.
  • Now, in the database and collection section, select the collection name
MongoDB atlas create index
  • For the use of the Visual Editor, click on Next.
  • Now review the default Atlas Search index configuration settings.
MongoDB atlas create an index
  • Click on the Create Search Index Button.
  • Now a model window appears, and it says that your index is building. Click on the Close button.
MongoDB atlas create an index example
  • A new index has been created and appears on the Search tab.
  • When the index is finished building, the status field reads Active.
Create index in MongoDB atlas with example

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.

StatusDescription
Not StartedBuilding of the index has not started in Atlas
Initial SyncAtlas Search does not serve queries
ActiveThe index is ready to use
RecoveringThis state usually occurs when the current replication point is no longer available.
FailedAtlas could not build the index
Delete in ProgressIn this Atlas, the index is from the cluster nodes.

Read: How to check if MongoDB is installed

Example 6: Creating an 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 an easy-to-traverse form.

Now, we will create an index in MongoDB Compass and gain a better understanding with the help of an example.

Example:

You need to follow the steps below 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
create index in mongodb compass
  • Click on the Indexes tab at the top of the window
  • The Indexes tab lists the existing indexes for a collection

For each index, Compass displays the following information:

ColumnDescription
Name and
Definition
The name of the index and keys.
TypeRegular, text, geospatial, or hashed index.
SizeHow large is the index?
UsagesThe number of times the index has been used
PropertiesAny special properties of the index?
how to create index in mongodb compass
  • Click on the CREATE INDEX button
  • Please enter the name of the index to create or leave it blank. MongoDB makes a default name for the index.
  • Add field to index

Specify an index key

  1. Select the field name from the dropdown list
  2. Specify a field that does not exist in any document as an index key, then enter the field name in the input box.
  3. To create a compound index, click Add Another Field.
  4. Use the dropdown to the right of each field name to specify the index type: ascending, descending, 2dsphere, and text.
  • Optional. Specify the index options

Compass supports the following index options:

OptionDescription
Build an index in
background
MongoDB deployment remains 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 that match the specified filter expression
Use Custom
Collation
Create a custom collation for the index using the options provided in Compass
Wildcard ProjectionSupport unknown or arbitrary fields that match the specified projection in the index

See the execution of execution in MongoDB Compass:

how to create compound index in mongodb compass
  • Now, click on the CREATE INDEX button.
how to create an index in mongodb

We successfully created indexes in MongoDB Compass. The Indexes are 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

Method 2: Using Python

When we create an index in a 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 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 a string for naming the index. We can also create multiple indexes.
  • Direction: It can be one or many directions, 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 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
res = doc.create_index("index_created")
print(res)

Here, we use the pymongo library to use MongoDB in Python. Additionally, use the MongoClient class from the pymongo library to establish the connection. After that, define the database and collection. The create_index() function is used for creating an index in Python.

See the execution of the above code:

Create index in MongoDB using python

Output:

After executing the code, it shows the following output:

index_created_1

Now, we have 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, 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 to use MongoDB in Python. Additionally, use the MongoClient class from the pymongo library to establish the connection. After that, define the 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:

create index mongodb python

Output:

After executing the code, it shows the following output:

index_descending_-1

Now, we have successfully created the index in descending order using Python.

Best Practices

Best PracticeExplanation
Index Fields Used in QueriesIndex fields that appear frequently in query filters.
Avoid Over-IndexingToo many indexes slow down writes and consume space.
Use Compound Indexes WiselyOrder fields in compound indexes based on query patterns.
Use Background IndexingBuild indexes without blocking database operations.
Monitor Index UsageUse MongoDB’s performance tools to identify unused indexes.
Use TTL Indexes for CleanupAutomatically remove expired data like sessions or logs.

Conclusion

Creating indexes in MongoDB is a foundational skill for optimizing database performance, handling large datasets, and complex queries. Whether you prefer the command line, programmatic methods, or GUI tools like MongoDB Compass, as mentioned in this article, will help you achieve this functionality.

You may also like to read the following topics.

Top 200 SQL Server Interview Questions and Answers

Free PDF On Top 200 SQL Server Interview Questions And Answers

Download A 40 pages PDF And Learn Now.