This is my compound index on my mongodb collection:
db.people.createIndex({ age: 1, height: 1 })
Both height and age can only be integer values.
query 1:
db.people.find({
age: { $gte: 25, $lte: 28 },
height: { $gte: 160, $lte: 180 }
})
query 2:
db.people.find({
age: { $in: [25, 26, 27, 28] },
height: { $gte: 160, $lte: 180 }
})
Is there any difference between query 1 and query 2 in terms of how efficiently it can use the compound index?
According to my experimentation on https://mongoplayground.net/, there is no difference in terms of number of seeks or number of keys examined. The explain plan is identical.
But it seems that it query 2 should be more efficient.
possible index entries:
25, 178
25, 179
25, 180
25, 181
25, 182
25, 183
...
26, 160
26, 161
...
If the index looks like the above, query 1 will walk from the first entry, (25, 178), down to (25, 180). But since it is a range filter, it doesn’t know what the next age is. Hence it must continue walking until it gets to (26, 160).
However, in query 2, since the query is given a list of explicit age values to look for, it knows that the next age value to seek is 26, and hence it should be able to seek the next key value, which is (26, 160), hence efficiently skipping the non-matching keys that query 1 has to walk through?
Questions:
- Is there any difference between the two queries in terms of index usage?
- If there isn’t, then what is wrong with my logic and reasoning to believe that there should be?