How to improve querying field in MongoDB?

To improve querying performance in MongoDB, you need to use indexes. Indexes create efficient data structures that allow MongoDB to quickly locate documents without scanning the entire collection.

Syntax

db.collection.createIndex({ "fieldName": 1 });
db.collection.find({ "fieldName": "searchValue" });

Sample Data

Let us create a collection with documents ?

db.improveQueryDemo.insertOne({
    "PlayerDetails": [
        {"PlayerName": "John", "PlayerGameScore": 5690},
        {"PlayerName": "Carol", "PlayerGameScore": 2690}
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5c9dbaf875e2eeda1d5c3670")
}

Display all documents from the collection ?

db.improveQueryDemo.find().pretty();
{
    "_id": ObjectId("5c9dbaf875e2eeda1d5c3670"),
    "PlayerDetails": [
        {
            "PlayerName": "John",
            "PlayerGameScore": 5690
        },
        {
            "PlayerName": "Carol",
            "PlayerGameScore": 2690
        }
    ]
}

Creating Index to Improve Performance

Create an index on the nested field to improve querying ?

db.improveQueryDemo.createIndex({"PlayerDetails.PlayerName": 1});
{
    "createdCollectionAutomatically": false,
    "numIndexesBefore": 1,
    "numIndexesAfter": 2,
    "ok": 1
}

Querying with Index

Now you can search efficiently by the exact match ?

db.improveQueryDemo.find({"PlayerDetails.PlayerName": "Carol"}).pretty();
{
    "_id": ObjectId("5c9dbaf875e2eeda1d5c3670"),
    "PlayerDetails": [
        {
            "PlayerName": "John",
            "PlayerGameScore": 5690
        },
        {
            "PlayerName": "Carol",
            "PlayerGameScore": 2690
        }
    ]
}

Key Points

  • Use createIndex() instead of the deprecated ensureIndex() method.
  • Ascending index (1) works efficiently for equality matches and range queries.
  • Indexes on nested fields use dot notation like "fieldName.nestedField".

Conclusion

Creating indexes on frequently queried fields dramatically improves MongoDB query performance. Use createIndex() with appropriate field paths to optimize your database operations.

Updated on: 2026-03-15T00:37:27+05:30

185 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements