Open In App
Related Articles

MongoDB – Index Types

Like Article
Save Article
Report issue

The beauty of a database lies in indexing i.e. fetching the data in a short span of time without iterating over the whole dataset. MongoDB is a NoSQL document type database that follows indexing. Indexes make searching in a collection is easier with the limited number of documents. A binary tree is the data structure used by an index. In documents, the _id field is a default index which is automatically created by MongoDB and we are not allowed to drop this index. If we try to drop this index using the dropIndexe() method it will give us an error. And the value of this field uniquely identifies a document from others. 

Create an Index :

Along with the default index, we can create indexes on our own using the createIndex() method. This method creates one or more indexes on the specified collections.

Syntax :

    keys : {Field_name:1/-1},

    options : <document>,

    commitQuorum : <string or integer>



In the following examples, we are working with:

Database: gfg

Collection: students

Document: Four documents that contains the details of the students


In the below image, first, we find the collection details. So, here collection name is students and in which we want to create an index over “studentId” column. 

Note: MongoDB is case-sensitive. So, studentId and studentid are treated differently.

On executing our query we got the message as “ok” meaning that an index is created and also “numIndexesAfter”: 2″ one index is already available(default index) and hence the count is increased by 2.

Types of index 

MongoDB provides different types of indexes that are used according to the data type or queries. The indexes supported by MongoDB is are as follows:

1. Single field Index: A single field index means index on a single field of a document. This index is helpful for fetching data in ascending as well as descending order. 


db.students.createIndex({“<fieldName>” : <1 or -1>});

Here 1 represents the field is specified in ascending order and -1 for descending order.



In this example we are creating a single index on studentsId field and the field is specified in ascending order.

2. Compound Index: We can combine multiple fields for compound indexing and that will help for searching or filtering documents in that way. Or in other words, the compound index is an index where a single index structure holds multiple references.


db.<collection>.createIndex( { <field1>: <type>, <field2>: <type2>, … } )

Here, we can combine the required fields in this pattern. Also the value of these fields is 1(for ascending order) or -1(for descending order).

Note: Compound indexes may have a single hashed index field but a hashing function is required by Hashed indexes to compute the hash of the value of the index field.


Here, we create a compound index on studentAge: 1, studentName:1

db.students.createIndex({studentAge: 1, studentName:1})


Here we are taking the sorting functionality based on “studentAge” followed by “studentName” fields and hence in the below image, though there are 2 documents matching for “studentAge = 25”, as studentName is an additional value given, as a second document, studentName with value “Geek40” is displayed and after that only, as a third document, studentName with value “GeeksForGeeksbest” is displayed. Hence, sometimes there will be a need to create compound indexes when we want to have a closer level of filtration.

3. Multikey Index: MongoDB uses the multikey indexes to index the values stored in arrays. When we index a field that holds an array value then MongoDB automatically creates a separate index of each and every value present in that array. Using these multikey indexes we can easily find a document that contains an array by matching the items. In MongoDB, you don’t need to explicitly specify the multikey index because MongoDB automatically determines whether to create a multikey index if the indexed field contains an array value. 


db.<collection>.createIndex( { <field>: <type>} )

Here, the value of the field is 1(for ascending order) or -1(for descending order).


In the students collection, we have three documents that contains array fields.

Now we create a multikey index:


Now we view the document that holds skillsets:[“Java”, “Android”]

db.students.find({skillsets:["Java", "Android"]}).pretty()

4. Geospatial Indexes: It is an important feature in MongoDB. MongoDB provides two geospatial indexes known as 2d indexes and 2d sphere indexes using these indexes we can query geospatial data. Here, the 2d indexes support queries that are used to find data that is stored in a two-dimensional plane. It only supports data that is stored in legacy coordinate pairs. Whereas 2d sphere indexes support queries that are used to find the data that is stored in spherical geometry. It supports data that is stored in legacy coordinate pairs as well as GeoJSON objects. It also supports queries like queries for inclusion, intersection, and proximity, etc.

Syntax of 2d sphere indexes:

db.<collection>.createIndex( { <Locationfield>: “2dsphere”} )


Let us assume the available data for “industries”

Now, let us create a 2d sphere index on the location field:{location:"2dsphere"})

Now, on the execution of the below query, we get
                $geometry:{type: "Point", coordinates:[-73.9667, 40.78]},
                $maxDistance: 5000

Here, the “$near” operator returns documents that are in the specified range of at least 1000 meters from and at most 5000 meters from the specified GeoJSON point, and hence we are getting only Tidal Park output. Similar to $near, it can support for $nearSphere, $geoWithin, $geoIntersects,$geoNear etc.,

5. Text Index: MongoDB supports query operations that perform a text search of string content. Text index allows us to find the string content in the specified collection. It can include any field that contains string content or an array of string items. A collection can contain at most one text index. You are allowed to use text index in the compound index.  


db.<collection>.createIndex( { <field>: “text”} )

We can give exact phrases also for searching by enclosing the search terms in double quotes

db.<collectionname>.find( { $text: { $search: “\”<Exact search term>\”” } } )

As here enclosed in double quotes, the search results contain only exact searched data.

In case, if we want to exclude a few texts in our search term, then we can do as 

db.<collectionname>.find( { $text: { $search: “<search terms> -<not required search terms>” } } )

Prepending a – character makes the search text to get ignored and the rest of the text is considered.

In the text search, the results are available in unsorted order. To make it available in sorted order of relevance score, $meta textScore field is needed and sort on it. Example:

  { $text: { $search: "Annisten" } },
  { score: { $meta: "textScore" } }
).sort( { score: { $meta: "textScore" } } )


In accessories collection we create text index:

db.accessories.createIndex({name: "text", description: "text"})

Now we display those documents that contain the string “Input”:

db.accessories.find({$text:{$search: "Input"}})

6. Hash Index: To maintain the entries with hashes of the values of the indexed field(mostly _id field in all collections), we use Hash Index. This kind of index is mainly required in the even distribution of data via sharding. Hashed keys are helpful to partition the data across the sharded cluster.


db.<collection>.createIndex( { _id: “hashed” } )

From Version 4.4 onwards, the compound Hashed Index is applicable

7. Wildcard Index: MongoDB supports creating indexes either on a field or set of fields and if the set of fields are mentioned, it is called as Wildcard Index. Generally, the wildcard index does not include _id field but if you what to include _id field in the wildcard index then you have to define it explicitly. MongoDB allows you to create multiple wildcard indexes in the given collection. Wildcard indexes support queries for unknown or arbitrary fields.


To create a wild card index on the specified field:

db.<collection>.createIndex( { “field.$**”:1 } )

To create a wild card index on all the field:

db.<collection>.createIndex( { “$**”:1 } )

To create a wild card index on multiple specified fields:


 { “$**”:1 }, 


{“field1”: 1, “field2”:2}



In book collection we create the wildcard index:

Let us create an index for “authorTags” field { "authorTags.$**" : 1 } )

Since “index” is created on set of fields, we can easily query in the following way { "authorTags.inclusions" : "RDBMS" } ) { "authorTags.usedin" : "Multipurpose" } )

Last Updated : 06 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Similar Reads