Create index in MongoDB

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:

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 descending index specifies 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 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:

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. 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:

Create index in MongoDB
Create index in MongoDB

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()
Create index in MongoDB query
Create index in MongoDB query

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:

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 descending index specifies 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 }
])

Here, we created multiple indexes at once on the name, cno, and speed fields and specify the direction key 1 for ascending order.

Execution:

Create multiple indexes in MongoDB
Create multiple indexes in MongoDB

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()
Create multiple indexes in MongoDB example
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.

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.

Create index in ascending order in MongoDB
Create index in ascending order in MongoDB

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

db.Details.getIndexes()
Create index in ascending order in MongoDB example
Create index in ascending order in MongoDB example

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:

Create index in descending order in MongoDB
Create index in descending order in MongoDB

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

db.Details.getIndexes()
Create index in descending order in MongoDB example
Create index in descending order in MongoDB example

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:

MongoDB create an index in a nested field
MongoDB create an index in a nested field

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.

MongoDB create an index in a nested field example
MongoDB create an index in a nested field example

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.

Create index in MongoDB atlas
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 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
Create index in MongoDB atlas example
Select the database and cluster
  • 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
Create an index in MongoDB atlas
Create Search Index
  • Now select the Configuration Method and click Next
Create index in MongoDB atlas
Select the Configuration Method
  • 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
MongoDB atlas create index
Choose the database and collection and enter the index name
  • For the use of Visual Editor click on Next.
  • Now review the default Atlas Search index configuration settings.
MongoDB atlas create an index
Review the default search index
  • 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.
MongoDB atlas create an index example
Search index build is now in progress
  • New created index appears on the Search tab.
  • When the index is finished building then status field reads Active.
Create index in MongoDB atlas with example
Successfully created the index in MongoDB Atlas

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 index is 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 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
Create index in MongoDB compass
Select the database and collection
  • 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:

ColumnDescription
Name and
Definition
The name of the index and keys.
TypeRegular, text, geospatial, or hashed index.
SizeHow large the index is.
UsagesThe number of times the index has been used
PropertiesAny special properties of the index.
How to create index in MongoDB compass
All the existing indexes for a collection
  • 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

  1. Select the field name from the dropdown list
  2. Specify a field if not exist in any document as 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, 2dsphare and text.
  • Optional. Specify the index options

Compass supports the following index options:

OptionDescription
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 ProjectionSupport unknown or arbitrary fields that match the specified projection in the index

See the execution of execution in MongoDB compass:

Create index in MongoDB compass example
Create index in MongoDB compass
  • Now click on CREATE INDEX button.
Create an index in MongoDB compass
Create an index in MongoDB compass

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:

Create index in MongoDB using python
Create index in MongoDB using python

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:

Create index in MongoDB using python example
Create index in MongoDB using python example

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.

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