Dhruv Gupta
Dhruv Gupta

Reputation: 13

MongoDB query involving some fields which are indexed and some which aren't

I am using indexes in MongoDB. I have a query such that:

db.collection.find({field1:"val1",field2:"val2",field3:"val3"})

where 'field1' and 'field2' are part of a compound index but 'field3' is not a part of any index. My question is will a collection scan be performed over the entire collection to match values for 'field3' OR will the presence of index on 'field1' and 'field2' restrict the number of documents to be scanned for value of 'field3'?

Thanks in advance for your time.

Upvotes: 1

Views: 96

Answers (1)

robjwilkins
robjwilkins

Reputation: 5652

Yes the index will be used

I tested this by creating a collection containing documents:

{ "a" : 1, "b" : 1, "c" : 1 }
{ "a" : 2, "b" : 2, "c" : 2 }
{ "a" : 3, "b" : 3, "c" : 3 }

And adding an index:

db.indexTest.createIndex({"a":1,"b":1})

Querying on field "c" alone returns an explain:

"winningPlan" : {
            "stage" : "COLLSCAN",
            "filter" : {
                "c" : {
                    "$eq" : 3
                }
            },
            "direction" : "forward"
        },

where as querying on "a", "b" and "c" returns an explain using an index:

"winningPlan" : {
            "stage" : "FETCH",
            "filter" : {
                "c" : {
                    "$eq" : 3
                }
            },
            "inputStage" : {
                "stage" : "IXSCAN",
                "keyPattern" : {
                    "a" : 1,
                    "b" : 1
                },
                "indexName" : "a_1_b_1",
                "isMultiKey" : false,
                "multiKeyPaths" : {
                    "a" : [ ],
                    "b" : [ ]
                },

Upvotes: 1

Related Questions