Tutorials Logic, IN info@tutorialslogic.com

MongoDB Indexes createIndex Performance: Tutorial, Examples, FAQs & Interview Tips

MongoDB Indexes createIndex Performance

MongoDB in MongoDB is best learned by connecting the rule to a product catalog or user activity store. Start with the smallest collection query, observe the output, and then add one realistic constraint so the concept becomes practical.

The key habit for this lesson is to watch document shape and index as it changes. That makes the topic easier to debug, easier to explain in interviews, and easier to use in real code without memorizing isolated syntax.

Why Indexes Matter

Without an index, MongoDB performs a collection scan - reading every document to find matches. On large collections this is extremely slow. An index stores a small, ordered subset of data that MongoDB can traverse quickly, similar to a book's index. The trade-off is slightly slower writes and additional storage.

Creating Indexes

Single Field, Compound, and Unique Indexes

Single Field, Compound, and Unique Indexes
// Single field index (1 = ascending, -1 = descending)
db.users.createIndex({ email: 1 })
db.users.createIndex({ age: -1 })

// Compound index - covers queries on multiple fields
db.users.createIndex({ role: 1, age: -1 })

// Unique index - enforces uniqueness
db.users.createIndex({ email: 1 }, { unique: true })

// Unique compound index
db.products.createIndex({ category: 1, sku: 1 }, { unique: true })

// Named index
db.users.createIndex({ email: 1 }, { name: "idx_email_unique", unique: true })

// List all indexes on a collection
db.users.getIndexes()

// Drop a specific index by name
db.users.dropIndex("idx_email_unique")

// Drop all indexes except _id
db.users.dropIndexes()

Multikey, Text, and Geospatial Indexes

Multikey, Text, Geospatial, and Hashed Indexes

Multikey, Text, Geospatial, and Hashed Indexes
// Multikey index - automatically created when indexing an array field
db.products.createIndex({ tags: 1 })
// Now queries like db.products.find({ tags: "mongodb" }) use the index

// Text index - for full-text search
db.articles.createIndex({ title: "text", body: "text" })
// Search using $text
db.articles.find({ $text: { $search: "mongodb tutorial" } })
// With relevance score
db.articles.find(
  { $text: { $search: "mongodb" } },
  { score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } })

// Geospatial index - for location-based queries
db.places.createIndex({ location: "2dsphere" })
// Find places within 5km of a point
db.places.find({
  location: {
    $near: {
      $geometry: { type: "Point", coordinates: [-73.97, 40.77] },
      $maxDistance: 5000
    }
  }
})

// Hashed index - for hash-based sharding
db.users.createIndex({ userId: "hashed" })

Sparse and TTL Indexes

Sparse Indexes and TTL (Time-To-Live) Indexes

Sparse Indexes and TTL (Time-To-Live) Indexes
// Sparse index - only indexes documents that have the field
// Useful for optional fields to save space
db.users.createIndex({ phone: 1 }, { sparse: true })

// TTL index - automatically deletes documents after a time period
// Expire sessions after 1 hour (3600 seconds)
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })

// Expire at a specific date stored in the document
db.events.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 })
// Document: { event: "sale", expiresAt: ISODate("2024-12-31T23:59:59Z") }

Analyzing Index Usage with explain()

Using explain() to Verify Index Usage

Using explain() to Verify Index Usage
// Basic explain - shows query plan
db.users.find({ email: "alice@example.com" }).explain()

// executionStats - shows actual execution metrics
db.users.find({ email: "alice@example.com" }).explain("executionStats")

// Key fields to check in explain output:
// winningPlan.stage: "IXSCAN" = index used, "COLLSCAN" = no index (slow!)
// executionStats.totalDocsExamined: should be close to nReturned
// executionStats.executionTimeMillis: query execution time

// Example output snippet:
// {
//   "winningPlan": { "stage": "FETCH", "inputStage": { "stage": "IXSCAN", "indexName": "email_1" } },
//   "executionStats": { "nReturned": 1, "totalDocsExamined": 1, "executionTimeMillis": 0 }
// }

// Hint - force MongoDB to use a specific index
db.users.find({ email: "alice@example.com" }).hint({ email: 1 })

Index Types Summary

Index Types Summary
// Single field:  { field: 1 } or { field: -1 }
// Compound:      { field1: 1, field2: -1 }
// Multikey:      { arrayField: 1 }  (auto-detected)
// Text:          { field: "text" }
// Geospatial:    { location: "2dsphere" } or { location: "2d" }
// Hashed:        { field: "hashed" }
// Unique:        { field: 1 }, { unique: true }
// Sparse:        { field: 1 }, { sparse: true }
// TTL:           { dateField: 1 }, { expireAfterSeconds: N }
// Partial:       { field: 1 }, { partialFilterExpression: { active: true } }
// Wildcard:      { "$**": 1 }  (indexes all fields)

Applied guide for MongoDB

Use MongoDB when the program needs a clear answer to a specific problem, not because the keyword looks familiar. In a real MongoDB task, first name the input, then name the transformation, then name the output. This small discipline shows whether the topic is being used correctly or only copied from an example.

A reliable practice flow is: create the smallest working collection query, add one normal case, add one edge case such as low-cardinality values and range filters, and then confirm the result with explain plan and sample documents. If the result surprises you, reduce the code until the behavior is visible again.

The most common trap here is building the index before checking the query pattern. Avoid it by writing one sentence before the code that explains why MongoDB is the right choice. After the code runs, verify the lesson by doing this: compare the plan before and after the index.

  • Identify the exact problem solved by MongoDB.
  • Trace document shape and index before and after the main operation.
  • Keep one intentionally broken version and explain the fix.
  • Connect the example to a product catalog or user activity store so the idea feels concrete.
Key Takeaways
  • I can explain where MongoDB fits inside a product catalog or user activity store.
  • I can point to the exact document shape and index affected by this topic.
  • I tested a normal case and an edge case involving low-cardinality values and range filters.
  • I verified the result with explain plan and sample documents instead of assuming it worked.
  • I can describe the main mistake: building the index before checking the query pattern.
Common Mistakes to Avoid
WRONG Building the index before checking the query pattern.
RIGHT Write the expected behavior first, then make the example prove it.
A one-line expectation turns the code from copied syntax into a testable idea.
WRONG Practicing only the perfect input.
RIGHT Also test low-cardinality values and range filters before considering the lesson complete.
The edge case is where most interview follow-up questions begin.
WRONG Looking only at the final output.
RIGHT Trace document shape and index through each important step.
Tracing makes debugging faster because you can see the first incorrect state.

Practice Tasks

  • Build one small collection query that demonstrates MongoDB in a product catalog or user activity store.
  • Change the example to include low-cardinality values and range filters and record the difference.
  • Break the example by deliberately building the index before checking the query pattern, then write the corrected version.
  • Explain the finished example in five bullet points: input, operation, output, failure case, and verification.

Frequently Asked Questions

Use it when the problem matches the behavior shown in the example and when the result can be verified through explain plan and sample documents.

Start with a tiny case, then test low-cardinality values and range filters. The main warning sign is building the index before checking the query pattern.

Trace document shape and index, predict the result, run the example, and compare your prediction with the actual output.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.