Types of Indexes in MongoDB

Last Updated : 5 May, 2026

Indexes in MongoDB speed up data retrieval by organizing field values for fast lookups, reducing full collection scans while using extra storage.

  • Improves query performance by enabling fast document lookup.
  • Uses a tree-based data structure for efficient searching.
  • Creates a default index on the _id field for every collection.
  • Stores sorted field values with references to matching documents.
  • Trades additional storage space for faster read operations.

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.createIndex(
{ fieldName: 1 | -1 },
options,
commitQuorum
)

Types

MongoDB provides different types of indexes that are used according to the data type or queries. The indexes supported by MongoDB 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.collection.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.

In the following examples, we are working with:

  • Database: gfg
  • Collection: students
  • Document: Four documents that contain the details of the students
Screenshot-2026-02-18-144956

Example: Creating a single index on studentsId field and the field is specified in ascending order.

db.students.createIndex({studentsId:1})
Screenshot-2026-02-18-145547

2. Compound Index: A compound index indexes multiple fields within a single index structure, enabling efficient filtering and searching on queries that reference those fields together.

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: Create a compound index on studentAge: 1, studentName:1

db.students.createIndex({studentAge: 1, studentName:1})
Screenshot-2026-02-18-145847

Query: Sorts documents by studentAge in ascending order and applies studentName as a secondary sort key for documents with equal ages.

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

Output:

Screenshot-2026-02-18-150242
  • Results are ordered by studentAge in ascending order (documents without studentAge appear first).
  • If multiple documents share the same studentAge, they are further sorted by studentName alphabetically.
  • This pattern benefits from a compound index on (studentAge, studentName) for better performance.

3. Multikey Index: MongoDB automatically creates multikey indexes when an indexed field contains an array, indexing each array element separately. This enables efficient querying of documents by matching values within arrays.

Syntax:

db.collection.createIndex( { <field>: <type>} )
  • 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.

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

Screenshot-2026-02-18-151441

Example: Create a multikey index.

db.students.createIndex({skillsets:1})
Screenshot-2026-02-18-151920

View the document that holds skillsets:["Java", "Android"]

db.students.find({skillsets:["Java", "Android"]})
Screenshot-2026-02-18-152009

4. Geospatial Indexes: Geospatial Index in MongoDB offers two types of geospatial indexes. 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"} )

The available data for "industries":

Screenshot-2026-02-18-152401

Example: Create a 2d sphere index on the location field.

db.industries.createIndex({location:"2dsphere"})
Screenshot-2026-02-18-152451

Query: Finds industries located within a specified distance range from a given geographic point using geospatial indexing.

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

Output:

Screenshot-2026-02-18-152936
  • $near returns locations within 1000–5000 meters of the given point.
  • Only Tidal Park falls in this range, so it is returned.
  • Locations outside the range are excluded.
  • Other supported geospatial operators include $nearSphere, $geoWithin, $geoIntersects, and $geoNear.

5. Text Index: MongoDB text indexes enable full-text search on string fields (including arrays of strings) each collection can have only one text index and it can be part of a compound index. 

Syntax:

db.collection.createIndex({ field: "text" })
  • Exact phrase searches can be performed by enclosing the search terms in double quotes.
db.collection.find({ $text: { $search: "\"Exact search term\"" } })
  • Performs an exact phrase search by matching only documents that contain the specified phrase enclosed in double quotes.
db.collection.find({ $text: { $search: "search terms -excludedTerm" } })
  • Performs a text search while excluding documents that contain the prefixed term from the results.

The available data for "accessories":

Screenshot-2026-02-18-155750

Example: Create text index.

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

Output:

Screenshot-2026-02-18-160108

Query: Display those documents that contain the string "Input".

db.accessories.find({$text:{$search: "Input"}})
Screenshot-2026-02-18-160314

6. Hash Index: A hashed index stores hash values of indexed field keys (commonly _id) and is primarily used in sharded clusters to evenly distribute data across shards for balanced partitioning and efficient routing.

Syntax:

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

From Version 4.4 onwards, the compound Hashed Index is applicable

7. Wildcard Index: MongoDB wildcard indexes index dynamic or unknown fields in documents, exclude _id by default (unless specified), and support multiple wildcard indexes per collection for flexible querying.

Syntax:

db.<collection>.createIndex({ "field.$**": 1 })
  • Create a wildcard index on a specific field path.
db.<collection>.createIndex({ "$**": 1 })
  • Create a wildcard index on all the field.
db.<collection>.createIndex(
{ "$**": 1 },
{ wildcardProjection: { field1: 1, field2: 1 } }
)
  • Create a wildcard index on selected fields using projection.

In book collection we create the wildcard index:

Screenshot-2026-02-18-161743

Create an index for "authorTags" field

db.book.createIndex( { "authorTags.$**" : 1 } )
Screenshot-2026-02-18-161844

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" } )
Screenshot-2026-02-18-162038

Best Practices for MongoDB Indexing

To ensure efficient database operations, follow these best practices:

  • Limit the Number of Indexes: Create only necessary indexes to balance read performance and write overhead.
  • Monitor Query Performance: Use explain() to ensure queries use the correct indexes.
  • Index Fields Used in Sorting: Add indexes on frequently sorted fields to improve performance.
  • Use Compound Indexes Carefully: Create compound indexes only for common multi-field queries to avoid storage overhead.
  • Avoid Over-Indexing in Write-Heavy Applications: Minimize indexes in write-heavy workloads to reduce write latency.
Comment
Article Tags:

Explore