MongoDB indexes not working when executing $elemMatch?

When MongoDB indexes don't appear to work with $elemMatch, use the explain() method to analyze query execution plans. The key issue is often that $elemMatch requires proper field path indexing and array structure understanding.

Syntax

db.collection.createIndex({"field.subfield": 1});
db.collection.find({"field": {$elemMatch: {"subfield": "value"}}}).explain();

Create Sample Data

First, create an index on the nested field and insert sample documents:

db.workingOfIndexesDemo.createIndex(
    {"Information.StudentDetails.StudentName": 1}, 
    {sparse: true, background: true}
);
{
    "createdCollectionAutomatically": true,
    "numIndexesBefore": 1,
    "numIndexesAfter": 2,
    "ok": 1
}
db.workingOfIndexesDemo.insertMany([
    {"Information": {"StudentDetails": {"StudentName": "Chris"}}},
    {"Information": {"StudentDetails": {"StudentName": "David"}}},
    {"Information": {"StudentDetails": {"StudentName": "Mike"}}}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e06f94825ddae1f53b621f7"),
        ObjectId("5e06f94f25ddae1f53b621f8"),
        ObjectId("5e06f95325ddae1f53b621f9")
    ]
}

Verify Data

db.workingOfIndexesDemo.find();
{"_id": ObjectId("5e06f94825ddae1f53b621f7"), "Information": {"StudentDetails": {"StudentName": "Chris"}}}
{"_id": ObjectId("5e06f94f25ddae1f53b621f8"), "Information": {"StudentDetails": {"StudentName": "David"}}}
{"_id": ObjectId("5e06f95325ddae1f53b621f9"), "Information": {"StudentDetails": {"StudentName": "Mike"}}}

Example: Using $elemMatch with explain()

Execute a query with $elemMatch and analyze the execution plan:

db.workingOfIndexesDemo.find({
    "Information.StudentDetails": {
        $elemMatch: {"StudentName": "David"}
    }
}).explain();
{
    "queryPlanner": {
        "plannerVersion": 1,
        "namespace": "test.workingOfIndexesDemo",
        "parsedQuery": {
            "Information.StudentDetails": {
                "$elemMatch": {
                    "StudentName": {"$eq": "David"}
                }
            }
        },
        "winningPlan": {
            "stage": "FETCH",
            "inputStage": {
                "stage": "IXSCAN",
                "keyPattern": {
                    "Information.StudentDetails.StudentName": 1
                },
                "indexName": "Information.StudentDetails.StudentName_1",
                "indexBounds": {
                    "Information.StudentDetails.StudentName": [
                        "["David", "David"]"
                    ]
                }
            }
        }
    }
}

Key Points

  • The IXSCAN stage confirms the index is being used effectively.
  • $elemMatch works with indexes when the field path matches the indexed field exactly.
  • Use explain("executionStats") for detailed performance metrics.
  • For array fields, ensure the index covers the specific nested path being queried.

Conclusion

MongoDB indexes work correctly with $elemMatch when properly configured. Use explain() to verify index usage and ensure field paths in queries match the indexed fields exactly.

Updated on: 2026-03-15T02:05:51+05:30

593 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements