MongoDb - MongoDB Indexing & Searching

MongoDB Indexing & Searching

Indexes in MongoDB improve query performance by allowing the database to find data faster instead of scanning every document (COLLSCAN). Searching relies heavily on indexes for speed and efficiency.


1. What is an Index in MongoDB?

An index is a data structure (usually a B-Tree) that stores references to documents based on specific fields, improving query performance.

  • Without Index → MongoDB scans all documents.

  • With Index → MongoDB jumps directly to matching documents.


2. Creating Indexes

Syntax

db.collection.createIndex({ field: 1 })  // Ascending
db.collection.createIndex({ field: -1 }) // Descending

Example

db.products.createIndex({ price: 1 })

This creates an ascending index on the price field.


3. Types of Indexes

A. Single Field Index

  • Indexes one field.

  • Best for simple queries.

db.users.createIndex({ age: 1 })

B. Compound Index

  • Indexes multiple fields.

  • Useful when filtering/sorting on multiple fields.

db.orders.createIndex({ customerId: 1, orderDate: -1 })

Query Example:

db.orders.find({ customerId: 123 }).sort({ orderDate: -1 })

Tip: Order of fields in compound indexes matters.


C. Unique Index

  • Ensures no duplicate values.

db.users.createIndex({ email: 1 }, { unique: true })

D. Text Index (For Full-Text Search)

Used to search words or phrases inside string fields.

db.articles.createIndex({ title: "text", content: "text" })

Example Query:

db.articles.find({ $text: { $search: "mongodb indexing" } })

Features:

  • Supports phrase search:

    db.articles.find({ $text: { $search: "\"mongodb indexing\"" } })
    
  • Exclude words:

    db.articles.find({ $text: { $search: "mongodb -charts" } })
    

E. Wildcard Index (For Dynamic Fields)

Used when documents have unknown or changing fields.

db.logs.createIndex({ "$**": 1 })

This creates an index on all fields.


F. TTL (Time-To-Live) Index

Automatically deletes documents after a set time.

db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })
  • Deletes documents 1 hour after createdAt.


G. Partial Index

Indexes only matching documents to save space.

db.orders.createIndex(
  { status: 1 },
  { partialFilterExpression: { status: "pending" } }
)

H. Sparse Index

Indexes only documents that contain the field.

db.users.createIndex({ phone: 1 }, { sparse: true })

4. Searching in MongoDB

MongoDB supports different search methods:


A. Basic Search

db.products.find({ price: 500 })

B. Range Queries (Works Best with Indexes)

db.products.find({ price: { $gte: 500, $lte: 1000 } })

C. Regex Search (Pattern Matching)

db.users.find({ name: { $regex: "^A", $options: "i" } })
  • ^A → Starts with A

  • $options: "i" → Case-insensitive


D. Text Search (Full-Text Search)

First, create a text index:

db.blogs.createIndex({ title: "text", content: "text" })

Then search:

db.blogs.find({ $text: { $search: "MongoDB charts" } })

E. Atlas Search (Recommended for Advanced Search)

MongoDB Atlas Search provides fast, relevant, ranked search.

Step 1 — Enable Atlas Search

  • Go to Atlas → Database → Search → Create Index.

Step 2 — Example Query

db.products.aggregate([
  {
    $search: {
      index: "productSearch",
      text: {
        query: "laptop",
        path: ["title", "description"]
      }
    }
  }
])

Features:

  • Fuzzy matching (laptplaptop)

  • Ranking & scoring

  • Supports synonyms


5. Checking Indexes

List All Indexes

db.products.getIndexes()

Check Query Performance

db.products.find({ price: 500 }).explain("executionStats")

Look for:

  • IXSCAN → Uses index (Good)

  • COLLSCAN → Collection scan (Slow)


6. Deleting Indexes

db.products.dropIndex("price_1")

Or drop all indexes:

db.products.dropIndexes()

7. Performance Best Practices

  • Always index fields used in:

    • find() filters

    • sort()

    • group() in aggregations

  • Use compound indexes for multi-field queries.

  • Use partial indexes for sparse data.

  • Avoid too many indexes — they slow down writes.

  • Prefer Atlas Search over $regex for large collections.

  • Monitor performance with:

    db.collection.explain("executionStats")
    

8. Indexing + Searching Example

Scenario: E-commerce products collection:

{
  "name": "iPhone 16",
  "category": "Mobile",
  "price": 1200,
  "description": "Latest Apple flagship phone"
}

Step 1 — Create Index

db.products.createIndex({ name: "text", description: "text", category: 1, price: 1 })

Step 2 — Search Products

db.products.find({ $text: { $search: "Apple phone" } }).sort({ price: 1 })

Step 3 — Check Query Plan

db.products.find({ $text: { $search: "Apple" } }).explain("executionStats")