#100DaysOfCodeChallenge

Day 36: A Comprehensive Guide to Indexing in MongoDB

MongoDB is one of the most popular NoSQL databases, known for its flexibility, scalability, and ease of use. However, as your application grows, so does the volume of data, which can lead to slower query performance. This is where indexing comes into play.

Indexes in MongoDB are special data structures that store a small portion of the data set in an easy-to-traverse form. They significantly enhance query performance by reducing the amount of data MongoDB needs to scan. In this blog, we’ll explore the different types of indexes, how to create and manage them, and best practices to keep your MongoDB queries blazing fast.


Why Indexing Matters

Imagine searching for a word in a book without an index. You’d have to go through every page until you find the word. Similarly, without indexes, MongoDB must scan every document in a collection to fulfill a query, leading to slower performance. Indexes help MongoDB quickly locate documents, minimizing the number of scanned documents.


Types of Indexes in MongoDB

MongoDB offers a variety of indexes to accommodate different use cases:

1. Single Field Index

This is the most basic type of index, created on a single field. It speeds up queries that filter or sort by that specific field.

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

The 1 denotes ascending order, while -1 denotes descending order.

2. Compound Index

Compound indexes are created on multiple fields, which is beneficial for queries that filter using more than one field.

js

CopyEdit

db.collection.createIndex({ field1: 1, field2: -1 })

The order of fields is crucial, as MongoDB can use the index to support queries that use a prefix of the indexed fields.

3. Multikey Index

This index is used for fields that hold array values. MongoDB creates an index entry for each element in the array.

js

CopyEdit

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

4. Text Index

Text indexes allow for efficient searching of string content within text fields. They’re ideal for search functionalities.

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

5. Geospatial Index

Geospatial indexes support queries of geospatial data, such as finding documents within a certain radius.

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

6. Hashed Index

Hashed indexes are used to distribute data evenly across shards in a sharded cluster.

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

100daysofcode lagos-mug