MongoDB Indexing & Search

MongoDB Tutorial

MongoDB Indexing & Search

In MongoDB Indexing & Search are used to speed up queries, and search features help you efficiently find data in large collections.

Without indexes, MongoDB performs a collection scan, which is slow for big data.


What is Indexing in MongoDB?

  • Index = special data structure

  • Improves query performance

  • Similar to index in a book

  • Stored separately from documents

 Trade-off: Faster reads, slightly slower writes


1️⃣ Create an Index

Syntax

Example: Index on name

Output:

{ acknowledged: true }

2️⃣ Types of Indexes in MongoDB

 Single Field Index


 Compound Index (Multiple Fields)

 Order matters in compound indexes.


 Unique Index

 Prevents duplicate values.


 Text Index (Search)

Used for full-text search.


 Hashed Index

Used in sharding.


3️⃣ View Indexes


4️⃣ Drop an Index

Or drop all:


5️⃣ Search Using Indexes

Normal Search

Uses index if available.


Range Search


6️⃣ Text Search (Full-Text Search)

Create Text Index (Once)

Search Text

Sort by Relevance


7️⃣ Explain Query (Check Index Usage)

Look for:

  • IXSCAN → index used

  • COLLSCAN → full collection scan


8️⃣ Indexing with Aggregation

 Index on course improves $match performance.


SQL vs MongoDB Indexing

SQLMongoDB
CREATE INDEXcreateIndex()
FULL TEXT SEARCHText Index
EXPLAIN PLANexplain()

Best Practices

  • Index frequently queried fields

  • Use compound indexes wisely

  • Avoid too many indexes

  • Always check with explain()

  • Place $match early in aggregation


Common Mistakes

  • Creating unnecessary indexes

  • Wrong field order in compound index

  • Expecting text index to behave like Google search


Quick Recap

You may also like...