Question 9 / 50
ImportantEasyConceptQuerying
When would you use $in rather than $or?
Think about it first.
Short answer
$in when you are testing one field against several values; $or when the conditions involve different fields. $in is easier to read and the planner handles it better.
Why?
An $or across different fields can only use an index if every branch is indexed; otherwise it degrades toward a collection scan. $in on a single indexed field is served by that one index.
Example
db.orders.find({ status: { $in: ["shipped", "delivered"] } })
db.orders.find({
$or: [{ status: "shipped" }, { amount: { $gt: 10000 } }]
})Interview tip
If every branch of an $or is the same field, rewrite it as $in before talking about indexes.
Common mistake
Writing $or: [{ city: 'Bangalore' }, { city: 'Mumbai' }] instead of $in.
How did you do?