0
0
MongodbHow-ToBeginner · 4 min read

How to Optimize Queries with Indexes in MongoDB

To optimize a query in MongoDB, create an index on the fields used in the query filter or sort. Use the createIndex() method to add indexes, which help MongoDB find data faster and reduce scanning the whole collection.
📐

Syntax

The basic syntax to create an index in MongoDB is:

  • db.collection.createIndex({ field: 1 }) creates an ascending index on field.
  • db.collection.createIndex({ field: -1 }) creates a descending index.
  • You can create compound indexes on multiple fields by listing them in the object.
mongodb
db.collection.createIndex({ field: 1 })
💻

Example

This example shows how to create an index on the username field to speed up queries filtering by username.

mongodb
use mydatabase

// Create an index on the username field
db.users.createIndex({ username: 1 })

// Query that benefits from the index
const result = db.users.find({ username: 'alice' })
printjson(result.toArray())
Output
[ { "_id": ObjectId("..."), "username": "alice", "email": "alice@example.com" } ]
⚠️

Common Pitfalls

Common mistakes when using indexes include:

  • Not creating indexes on fields used in queries, causing full collection scans.
  • Creating too many indexes, which slows down writes.
  • Using indexes on fields with low cardinality (few unique values), which may not improve performance.
  • Forgetting to analyze query plans with explain() to verify index usage.
mongodb
/* Wrong: Query without index */
db.users.find({ email: 'bob@example.com' })

/* Right: Create index first */
db.users.createIndex({ email: 1 })
db.users.find({ email: 'bob@example.com' })
📊

Quick Reference

ActionCommand ExampleDescription
Create ascending indexdb.collection.createIndex({ field: 1 })Index on field in ascending order
Create descending indexdb.collection.createIndex({ field: -1 })Index on field in descending order
Create compound indexdb.collection.createIndex({ field1: 1, field2: -1 })Index on multiple fields
Check query plandb.collection.find(query).explain()See if index is used
List indexesdb.collection.getIndexes()Show all indexes on collection

Key Takeaways

Create indexes on fields used in query filters or sorting to speed up queries.
Use db.collection.createIndex() to add indexes in MongoDB.
Avoid too many indexes to prevent slowing down write operations.
Check query plans with explain() to ensure indexes are used.
Indexes on low-cardinality fields may not improve performance.