How to improve the execution time of a query in MongoDB?

To improve the execution time of a query in MongoDB, use indexes on frequently queried fields. Indexes create efficient data structures that allow MongoDB to quickly locate documents without scanning the entire collection.

Syntax

db.collection.createIndex({ "fieldName": 1 }, { unique: true });
db.collection.find({ "fieldName": "value" });

Create Sample Data with Index

First, create a unique index on the LastName field for faster queries ?

db.demo193.createIndex({"LastName": 1}, {unique: true});
{
    "createdCollectionAutomatically": true,
    "numIndexesBefore": 1,
    "numIndexesAfter": 2,
    "ok": 1
}

Insert sample documents ?

db.demo193.insertMany([
    {"FirstName": "John", "LastName": "Doe"},
    {"FirstName": "John", "LastName": "Smith"},
    {"FirstName": "David", "LastName": "Miller"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e3ade1803d395bdc21346d1"),
        ObjectId("5e3ade1f03d395bdc21346d2"),
        ObjectId("5e3ade2803d395bdc21346d3")
    ]
}

Display All Documents

db.demo193.find();
{ "_id": ObjectId("5e3ade1803d395bdc21346d1"), "FirstName": "John", "LastName": "Doe" }
{ "_id": ObjectId("5e3ade1f03d395bdc21346d2"), "FirstName": "John", "LastName": "Smith" }
{ "_id": ObjectId("5e3ade2803d395bdc21346d3"), "FirstName": "David", "LastName": "Miller" }

Fast Query Using Index

Query using the indexed field for optimal performance ?

db.demo193.find({"LastName": "Smith"});
{ "_id": ObjectId("5e3ade1f03d395bdc21346d2"), "FirstName": "John", "LastName": "Smith" }

Key Points

  • Indexes dramatically reduce query execution time by avoiding full collection scans.
  • Unique indexes ensure data integrity while providing fast lookups.
  • Index the fields you query most frequently for best performance.

Conclusion

Creating indexes on frequently queried fields is the most effective way to improve MongoDB query performance. The index allows MongoDB to quickly locate documents without scanning the entire collection.

Updated on: 2026-03-15T01:42:12+05:30

305 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements