Creating indexes in MongoDB is crucial for improving query performance, especially as your dataset grows. Indexes help MongoDB quickly locate and access the required data without scanning the entire collection, making read operations more efficient. In this section, we’ll walk through how to create different types of indexes in MongoDB, how to manage them, and best practices for creating and using indexes effectively.
A single-field index is an index on one field of a document. It’s the most basic type of index and speeds up queries that filter or sort by a specific field.
javascript
Copy code
db.collection.createIndex({ fieldName: 1 }) // Ascending index (1) db.collection.createIndex({ fieldName: -1 }) // Descending index (-1)
Creating an index on the name
field in ascending order:
javascript
Copy code
db.users.createIndex({ name: 1 })
This index will speed up queries that filter or sort by name
, for example:
javascript
Copy code
db.users.find({ name: "Alice" })
A compound index is an index on multiple fields. Compound indexes are used when your queries filter on multiple fields, and they can optimize queries that use any of the fields in the index.
javascript
Copy code
db.collection.createIndex({ field1: 1, field2: -1 })
The order of fields in a compound index is important. MongoDB uses the index to efficiently filter or sort based on the left-most field in the index.
Creating a compound index on firstName
(ascending) and lastName
(descending):
javascript
Copy code
db.users.createIndex({ firstName: 1, lastName: -1 })
This index will speed up queries like:
javascript
Copy code
db.users.find({ firstName: "John", lastName: "Doe" }) db.users.find({ firstName: "John" }).sort({ lastName: -1 })
A multikey index is used when a field contains an array. MongoDB creates a separate index entry for each element of the array, allowing for efficient querying of documents with arrays.
javascript
Copy code
db.collection.createIndex({ fieldName: 1 })
If the fieldName
is an array, MongoDB will automatically create a multikey index.
Creating a multikey index on a tags
array field:
javascript
Copy code
db.posts.createIndex({ tags: 1 })
This index will speed up queries like:
javascript
Copy code
db.posts.find({ tags: "mongodb" })
A text index allows for text search on string fields. MongoDB supports full-text search, which includes word stemming, tokenization, and case-insensitive searches.
javascript
Copy code
db.collection.createIndex({ fieldName: "text" })
You can create a text index on one or more fields. MongoDB automatically indexes all string fields as part of the text index.
Creating a text index on the description
field:
javascript
Copy code
db.products.createIndex({ description: "text" })
This index will support text search queries:
javascript
Copy code
db.products.find({ $text: { $search: "laptop" } })
You can also use the $text
operator to find documents with text that matches specific words or phrases.
A hashed index is used for sharding or for equality queries that require fast lookups by hash value.
javascript
Copy code
db.collection.createIndex({ fieldName: "hashed" })
Creating a hashed index on the userId
field:
javascript
Copy code
db.users.createIndex({ userId: "hashed" })
Hashed indexes are typically used in sharded collections where the shard key is hashed to distribute data across different shards.
MongoDB supports geospatial queries. A geospatial index allows you to index geographical data, such as coordinates, to perform location-based queries (e.g., finding documents near a given point).
2dsphere
index:javascript
Copy code
db.collection.createIndex({ location: "2dsphere" })
Creating a 2dsphere
index on a location
field to store geographic coordinates:
javascript
Copy code
db.places.createIndex({ location: "2dsphere" })
This index enables queries like:
javascript
Copy code
db.places.find({ location: { $nearSphere: { $geometry: { type: "Point", coordinates: [ -73.9667, 40.78 ] }, $maxDistance: 1000 } } })
A TTL index automatically removes documents from the collection after a specified period of time. This is useful for managing documents with an expiration time (e.g., session data, logs).
javascript
Copy code
db.collection.createIndex({ fieldName: 1 }, { expireAfterSeconds: <seconds> })
Creating a TTL index on a createdAt
field to expire documents after 3600 seconds (1 hour):
javascript
Copy code
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })
This index automatically removes expired session documents after one hour, keeping your data fresh without manual intervention.
A wildcard index allows you to index all fields within a document, which is useful when the document structure is dynamic and fields are added/removed over time.
javascript
Copy code
db.collection.createIndex({ "$**": 1 })
Creating a wildcard index on all fields in a document:
javascript
Copy code
db.users.createIndex({ "$**": 1 })
This type of index is useful when your documents have dynamic structures, and you want to search any field in the document.
You can list all indexes in a collection using the getIndexes()
method.
javascript
Copy code
db.collection.getIndexes()
To drop an index, use the dropIndex()
method. You can specify the index by its name or its index specification.
javascript
Copy code
db.collection.dropIndex("indexName") // Drop by name db.collection.dropIndex({ fieldName: 1 }) // Drop by field
To drop all indexes (except the default _id
index), use dropIndexes()
:
javascript
Copy code
db.collection.dropIndexes()
explain()
to Analyze Queries: Use the explain()
method to analyze your queries and ensure that the indexes are being used effectively.javascriptCopy codedb.collection.find({ fieldName: "value" }).explain("executionStats")
Indexes are essential for optimizing query performance in MongoDB, especially as data grows. Understanding which types of indexes to use and when to use them can help ensure that your application remains responsive as your dataset scales. Always test and monitor your indexes using tools like explain()
to make sure you’re getting the best performance from your MongoDB queries.