Open In App

MongoDB – Index Types

Last Updated : 17 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In MongoDB, the power of efficient data retrieval lies in indexing. Indexes are crucial for optimizing query performance, making it faster to retrieve specific data from large collections without scanning every document.

MongoDB, a NoSQL database, uses a binary tree data structure for indexing, ensuring rapid access to data. By default, MongoDB creates an index on the _id field for every document, which uniquely identifies each document in the collection.

What is an Index in MongoDB?

An index in MongoDB is a data structure that improves the speed of data retrieval operations on a collection at the cost of additional storage space. When we create an index on a field in MongoDB, the database stores a sorted map of that field’s values along with references to the documents that contain those values. This allows MongoDB to quickly locate documents based on the indexed field.

How to Create an Index in MongoDB

We can create custom indexes using the createIndex() method. This method enables us to optimize queries based on specific fields.

Syntax :

db.Collection.name.createIndex(

    keys : {Field_name:1/-1},

    options : <document>,

    commitQuorum : <string or integer>

)

Examples of MongoDB Index Types

In the following examples, we are working with:

  • Database: gfg
  • Collection: students
  • Document: Four documents that contains the details of the students
db.students.createIndex({studentsId:1})

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. 

Syntax:

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

  • 1 represents ascending order, meaning that MongoDB will store the values in increasing order.
  • -1 can be used for descending order.
  • Ideal for querying or sorting based on a single field, such as searching for a student’s studentId.

Example:

db.students.createIndex({studentsId:1})

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.

Syntax:

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

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.

Example:

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

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

db.students.find().sort({"studentAge":1,"studentName":1}).pretty()

Explanation: 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, we 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. 

Syntax:

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

  • Here, the value of the field is 1(for ascending order) or -1(for descending order).
  • Ideal for queries that search for specific values within an array, such as finding students who possess certain skills.

Example:

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

Now we create a multikey index:

db.students.createIndex({skillsets:1})

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

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

4. Geospatial Indexes: Geospatial Index MongoDB offers two types of geospatial indexes: 2d and 2dsphere. These are used for storing and querying geospatial data (coordinates and geographical locations).

  • 2d Index: Used for querying legacy coordinate pairs on a 2D plane.
  • 2dsphere Index: Supports both 2D plane coordinates and GeoJSON objects, allowing for spherical geometry queries.

Syntax of 2d sphere indexes:

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

Example:

Let us assume the available data for “industries”

Now, let us create a 2d sphere index on the location field:

db.industries.createIndex({location:"2dsphere"})

Now, on the execution of the below query, we get

db.industries.find(
{
location:
{$near:
{
$geometry:{type: "Point", coordinates:[-73.9667, 40.78]},
$minDistance:1000,
$maxDistance: 5000
}
}
}
}.pretty()

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. We are allowed to use text index in the compound index.  

Syntax:

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:

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

Example:

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.

Syntax:

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

From Version 4.4 onwards, the compound Hashed Index is applicable

7. Wildcard Index: MongoDB allows the creation of Wildcard Indexes, which can index either a single field or a set of fields within a collection. When multiple fields are indexed together, it’s referred to as a Wildcard Index. By default, the _id field is not included in a wildcard index.

However, if we want to include the _id field in the wildcard index, we must specify it explicitly. MongoDB also allows us to create multiple wildcard indexes within a collection, making it suitable for querying arbitrary or unknown fields. This flexibility enables efficient querying of dynamic data structures in our database.

Syntax:

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:

db.<collection>.createIndex(

 { “$**”:1 }, 

{“wildcardProjection”:

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

})

Example:

In book collection we create the wildcard index:

Let us create an index for “authorTags” field

db.book.createIndex( { "authorTags.$**" : 1 } )

Since “index” is created on set of fields, we can easily query in the following way

db.book.find( { "authorTags.inclusions" : "RDBMS" } )
db.book.find( { "authorTags.usedin" : "Multipurpose" } )

Best Practices for MongoDB Indexing

To ensure efficient database operations, follow these best practices:

1. Limit the Number of Indexes: Indexes improve read performance but slow down write operations. Use only the necessary indexes that support our most frequent queries.

2. Monitor Query Performance: Regularly use the explain() method to analyze the efficiency of your queries and ensure they are utilizing the correct indexes.

3. Index Fields Used in Sorting: If queries often involve sorting on specific fields, create indexes on those fields to speed up the sorting process.

4. Use Compound Indexes Carefully: Compound indexes are useful for queries that involve multiple fields. However, creating unnecessary compound indexes can increase storage overhead.

5. Avoid Over-Indexing in Write-Heavy Applications: Too many indexes can significantly affect performance in write-heavy applications. Be strategic in indexing only the fields that improve query performance.

Conclusion

MongoDB indexing plays a crucial role in optimizing query performance, particularly when dealing with large datasets. Understanding the different types of indexes such as single field, compound, multikey, geospatial, text, hashed, and wildcard indexes can significantly enhance the speed of our database queries. By implementing the right indexes based on our use case and query patterns, we can ensure efficient data retrieval, faster search operations, and better overall performance in our MongoDB database.

FAQs

What are the different types of indexes in MongoDB?

MongoDB supports several index types, including single field, compound, multikey, geospatial, text, hashed, and wildcard indexes, each optimized for different query use cases.

What are the different types of indexing?

Indexing types include B-tree indexing (default), Hash indexing, Full-text indexing, Geospatial indexing, and Wildcard indexing, used for various data types and query optimizations.

Which indexes are being used in MongoDB?

MongoDB uses B-tree indexes by default, along with specialized indexes like geospatial for location-based queries, text for full-text searches, and hashed for sharding key-based queries.

How many indexes should I use in MongoDB?

The number of indexes depends on query performance needs. While indexes speed up query execution, too many indexes can slow down write operations. It’s recommended to use only the indexes that directly support frequently queried fields



Next Article
Article Tags :

Similar Reads

three90RightbarBannerImg