Understanding MongoDB Query Plan

To understand how MongoDB executes queries, use the explain() method. Query plans show the execution strategy, including which indexes are used and performance statistics for query optimization.

Syntax

db.collection.explain().find(query);
db.collection.explain("executionStats").find(query);
db.collection.explain("allPlansExecution").find(query);

Sample Data

Let us create a collection with documents and an index ?

db.demo408.insertMany([
    {"Value": 50},
    {"Value": 20},
    {"Value": 45},
    {"Value": 35}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e70e3a115dc524f70227678"),
        ObjectId("5e70e3a715dc524f70227679"),
        ObjectId("5e70e3ac15dc524f7022767a"),
        ObjectId("5e70e3af15dc524f7022767b")
    ]
}

Create an index on the Value field ?

db.demo408.createIndex({Value: 1});
{
    "createdCollectionAutomatically": false,
    "numIndexesBefore": 1,
    "numIndexesAfter": 2,
    "ok": 1
}

Example: Basic Query Plan

Get the query plan for finding documents with Value greater than 40 ?

db.demo408.explain().find({Value: {$gt: 40}});
{
    "queryPlanner": {
        "plannerVersion": 1,
        "namespace": "test.demo408",
        "indexFilterSet": false,
        "parsedQuery": {
            "Value": {
                "$gt": 40
            }
        },
        "winningPlan": {
            "stage": "FETCH",
            "inputStage": {
                "stage": "IXSCAN",
                "keyPattern": {
                    "Value": 1
                },
                "indexName": "Value_1",
                "isMultiKey": false,
                "direction": "forward",
                "indexBounds": {
                    "Value": [
                        "(40.0, inf.0]"
                    ]
                }
            }
        },
        "rejectedPlans": []
    },
    "serverInfo": {
        "host": "DESKTOP-QN2RB3H",
        "port": 27017,
        "version": "4.0.5"
    },
    "ok": 1
}

Key Plan Components

  • stage: "IXSCAN" − Uses index scan (efficient)
  • stage: "FETCH" − Fetches full documents after index lookup
  • indexName: "Value_1" − Shows which index was used
  • indexBounds − Range of values scanned in the index
  • rejectedPlans − Alternative plans considered but not used

Conclusion

The explain() method reveals MongoDB's query execution strategy, helping optimize performance by showing index usage and execution stages. Use it to identify slow queries that need indexing or optimization.

Updated on: 2026-03-15T02:53:24+05:30

604 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements