Blog

Create Index | MongoDB Indexing Tutorial

Compound Index | MongoDB Indexing Tutorial

Index Performance | MongoDB Indexing Tutorial

Indexing Types | MongoDB Indexing Tutorial

Unique Index | MongoDB Indexing Tutorial

List Indexes | MongoDB Indexing Tutorial

Create Index | MongoDB Indexing Tutorial

Key Takeaways

  • Indexes in MongoDB dramatically improve query performance by allowing the database to quickly locate data.
  • Use different index types for specific cases: single field, compound, multikey, text, and geospatial.
  • Aim to index fields that are most queried to balance performance with storage and update costs.

Prefix: Why Use Indexes in MongoDB?

Indexes let you query collections far more efficiently without making MongoDB scan entire datasets. They can be the difference between waiting seconds versus milliseconds for query results, especially with large datasets.

Suppose you have a users collection with 100 million records in MongoDB. Running a simple query like this:

db.getCollection('users').find({age:{$lt:30}})

would take MongoDB several seconds, as it needs to evaluate each record. Creating an index on the age field:

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

enables the database to use this B-Tree structured index to find results significantly faster.

How does indexing work?

Indexes replicate parts of collection data into a sorted structure (a B-Tree). This allows quick lookups without full collection scans. However, there’s a cost when maintaining indexes since they must update with new inserts, increasing storage size. Use them wisely, focusing on the fields you query most often.

Create a Single Field Index

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

Creates an index on the age field in ascending order. While order is specified, for single field indexes, it ultimately doesn’t affect performance.

When should you use a single field index?

Employ single field indexes when queries frequently target a specific field, improving retrieval speed.

Create a Compound Index

db.getCollection('users').createIndex({email:1, name:-1})

Supports queries involving multiple fields, like:

db.getCollection('users').find({email:"alex@gmail.com", name:"Sam"})

Ordering fields in the index is crucial to its utility; MongoDB can use a compound index only if queries begin with the first indexed field.

Create a Multikey Index

MongoDB automatically creates multikey indexes for fields holding arrays. Consider this data structure:

{
  "_id": ObjectId("62577886b29616254381f6b9"),
  "altInfo": [
    { "otherEmail": "foo@example.com" },
    { "otherEmail": "bar@example.com" },
  ]
}

The database creates a multikey index automatically if indexed like:

db.getCollection('documents').createIndex({"altInfo.otherEmail":1})

Limitations to Multikey Indexes

These indexes don’t support fields that are both arrays in a compound index. For example, indexing two array fields together won’t work.

Create a Text Index

db.getCollection('documents').createIndex({name:"text"})

Facilitates searching string fields using the $text operator:

db.getCollection('documents').find({$text: {$search: "Vincent"}})

Only one text index per collection is allowed, but can cover multiple fields.

Create a Wildcard Index

db.getCollection('documents').createIndex({"altInfo.$**":1})

Indexes subfields/attributes flexibly. Wildcard indexes are powerful but come at a performance cost during database operations.

Other Index Types

Supporting Geospatial Queries

Index geospatial data, using GeoJSON or legacy coordinates, if your application requires spatial calculations.

2dsphere Indexes

db.getCollection('documents').createIndex({location:"2dsphere"})

Utilize these indexes when performing queries involving earth-like geometries.

Hashed Indexes

db.getCollection('documents').createIndex({_id:"hashed"})

Ideal for indexing data across sharded clusters efficiently.

Conclusion

Crafting a robust indexing strategy is key to effective MongoDB use. Analyze your application's query patterns to decide which indexes provide performance without exorbitant costs. Optimization lies in balancing query speed against storage and maintenance overheads.

FAQ

What is the impact of indexing on database size?

Indexes increase the required storage because they replicate data in structured ways (B-Trees), adding overhead to maintain them.

Can I remove an index if not needed later?

Yes. You can drop an index to revert the collection to an unindexed state, reducing storage and maintenance costs.

How do I choose which fields to index?

Index fields you query frequently — especially in large datasets — where reducing scan times would significantly benefit performance.

Mastering the tech interviewWhat everyone is doing wrong in tech interviews