0
0
MongoDBquery~3 mins

Why Sparse indexes in MongoDB? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your database could skip the clutter and find only what really matters instantly?

The Scenario

Imagine you have a huge collection of documents where only some have a certain field, like 'email'. You want to quickly find documents with emails, but many documents don't have this field at all.

The Problem

Without sparse indexes, searching for documents with 'email' means scanning everything, including those without 'email'. This wastes time and slows down your queries, especially as your data grows.

The Solution

Sparse indexes only include documents that have the indexed field. This means your searches skip documents missing that field, making queries faster and indexes smaller.

Before vs After
Before
db.collection.createIndex({ email: 1 })
After
db.collection.createIndex({ email: 1 }, { sparse: true })
What It Enables

It enables fast, efficient queries on fields that are not present in every document, saving space and time.

Real Life Example

A user database where only some users have a 'phoneNumber' field. Using a sparse index on 'phoneNumber' lets you quickly find users who provided their phone number without indexing everyone.

Key Takeaways

Sparse indexes include only documents with the indexed field.

This reduces index size and speeds up queries on optional fields.

Ideal for fields that many documents might not have.