Indexing in MongoDB

Understanding the importance of indexing for query performance and how to create and manage indexes on collections.


MongoDB Essentials: Understanding Indexes

Indexes in MongoDB are special data structures that store a small portion of the collection's data in an easy to traverse form. Indexes store the value of specific fields or sets of fields, ordered by the value of the field as specified in the index. MongoDB can use indexes to efficiently locate documents without scanning the entire collection. This significantly improves query performance. Without indexes, MongoDB must perform a collection scan, checking every document in a collection to select those that match the query statement.

Types of Indexes in MongoDB

MongoDB offers a variety of index types to support different types of queries and workloads. Here's an exploration of some key index types:

1. Single Field Indexes

A single field index indexes a single field in a document. These are the simplest type of index and are useful for queries that filter or sort based on the value of a single field.

Example: Create an index on the username field.

db.collection.createIndex( { username: 1 } )
  • 1 specifies ascending order for the index. You can also use -1 for descending order.

2. Compound Indexes

A compound index indexes multiple fields in a document. The order of fields in the compound index definition is significant. Queries can efficiently use compound indexes to filter and sort on multiple fields. The prefix of a compound index is also useable.

Example: Create an index on age and then city.

db.collection.createIndex( { age: 1, city: 1 } )

This index can support queries that filter on both age and city, or just age.

3. Multikey Indexes

Multikey indexes index fields that hold arrays. If you index a field that holds an array, MongoDB creates separate index entries for each element of the array. This allows queries to efficiently search for specific values within arrays.

Example: Create an index on the tags array field.

db.collection.createIndex( { tags: 1 } )

4. Geospatial Indexes

Geospatial indexes are used to efficiently query and analyze geospatial data. MongoDB supports two types of geospatial indexes: 2d indexes for legacy coordinate pairs and 2dsphere indexes for GeoJSON objects. 2dsphere indexes support more complex geospatial operations.

Example (2dsphere): Create a 2dsphere index on the location field (assuming it stores GeoJSON data).

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

5. Text Indexes

Text indexes support text search queries on string content. You can create a text index on one or more string fields, enabling efficient full-text search within your documents.

Example: Create a text index on the description field.

db.collection.createIndex( { description: "text" } )

You can also index multiple fields for text search.

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