Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is to be done when MongoDB takes too much time to find the record?
To reduce the time to find records in MongoDB, you can use indexes. Indexes create shortcuts to your data, dramatically improving query performance by avoiding full collection scans.
Syntax
db.collection.createIndex({fieldName: indexType});
Sample Data
db.employees.insertMany([
{"EmployeeName": "John Doe", "Department": "Engineering", "Salary": 75000},
{"EmployeeName": "Jane Smith", "Department": "Marketing", "Salary": 65000},
{"EmployeeName": "Mike Johnson", "Department": "Sales", "Salary": 55000}
]);
Method 1: Single Field Index (Most Common)
Create an ascending index on a frequently queried field ?
db.employees.createIndex({"EmployeeName": 1});
{
"createdCollectionAutomatically": true,
"numIndexesBefore": 1,
"numIndexesAfter": 2,
"ok": 1
}
The 1 specifies ascending order. Use -1 for descending order.
Method 2: Text Index for Search Queries
Create a text index for full-text search capabilities ?
db.employees.createIndex({"EmployeeName": "text"});
{
"createdCollectionAutomatically": true,
"numIndexesBefore": 1,
"numIndexesAfter": 2,
"ok": 1
}
Text indexes enable efficient text searches using $text operator.
Method 3: Hashed Index for Equality Queries
Create a hashed index for random distribution in sharded environments ?
db.employees.createIndex({"EmployeeName": "hashed"});
{
"createdCollectionAutomatically": true,
"numIndexesBefore": 1,
"numIndexesAfter": 2,
"ok": 1
}
Hashed indexes are ideal for equality queries and sharding.
Verify Index Performance
Use explain() to verify index usage ?
db.employees.find({"EmployeeName": "John Doe"}).explain("executionStats");
Key Points
- Single field indexes are best for exact matches and range queries
- Text indexes enable full-text search but have storage overhead
- Hashed indexes provide even distribution for sharding
- Create indexes on fields you query most frequently
Conclusion
Indexes are essential for MongoDB performance optimization. Choose the appropriate index type based on your query patterns - single field for exact matches, text for search, and hashed for sharding scenarios.
