Compound Index:
{
"A": 1,
"C": 1,
"D": 1,
"E": 1,
"F": 1,
"G": 1,
"H": 1,
"I": 1,
"B": 1
}
Fast query:
const result = await sandbox
.aggregate([
{
$match: {
A: { $in: [1, 2] },
C: { $in: [1, 2] },
D: { $in: [1, 2] },
E: { $in: [1, 2] },
F: { $in: [1, 2] },
G: { $in: [1, 2] },
H: { $in: [1, 2] },
I: { $in: [1, 2] },
B: { $eq: 500 },
},
},
])
The query becomes significantly slower if it is modified to be this:
const result = await sandbox
.aggregate([
{
$match: {
$or: [{ A: { $eq: 1 } }, { A: { $eq: 2 } }],
$or: [{ C: { $eq: 1 } }, { C: { $eq: 2 } }],
$or: [{ D: { $eq: 1 } }, { D: { $eq: 2 } }],
$or: [{ E: { $eq: 1 } }, { E: { $eq: 2 } }],
$or: [{ F: { $eq: 1 } }, { F: { $eq: 2 } }],
$or: [{ G: { $eq: 1 } }, { G: { $eq: 2 } }],
$or: [{ H: { $eq: 1 } }, { H: { $eq: 2 } }],
$or: [{ I: { $eq: 1 } }, { I: { $eq: 2 } }],
B: { $eq: 500 },
},
},
])
What is the reason for this?
EDITED:
After using explain
, it is confirmed that in the fast query, the index was scanned while in the slow query with $or
statement, the collection scan was used.
Now the question becomes, why isn't MongoDB able to use the index scan with $or
conditions.