I’m experimenting with compound indexes in MongoDB and noticed some behavior I want to clarify.
Suppose I have a compound index like this:
db.users.createIndex({ gender: 1, city: 1, age: 1 })
When I run a query that specifies the first and last field but skips the middle one, for example:
db.users.find({ gender: "M", age: { $gt: 25 } }).explain("executionStats")
The indexBounds in the explain plan shows something like:
gender: [ "M", "M" ]
city: [ MinKey, MaxKey ]
age: (25, MaxKey]
This seems to indicate that MongoDB automatically substitutes missing in-between fields with [MinKey, MaxKey] so the index can still be used.
My questions are:
-
Is it guaranteed that whenever a middle field in a compound index is missing from the query, MongoDB will substitute [MinKey, MaxKey] in the indexBounds?
-
As long as the leading field of a compound index is included in the query, is it guaranteed that the index can be used?
-
Are there any exceptions to these behaviors (e.g., with range queries, sort, partial indexes, or newer MongoDB versions)?
I want to understand whether this is a fundamental rule of how MongoDB compound indexes work, or if it’s just an observed implementation detail.