Question 11 / 50
ImportantMediumDebuggingQuerying
This user search is fine in development and unusable in production. What would you investigate?
db.users.find({
name: { $regex: /rah/i }
})Think about it first.
Short answer
A leading-wildcard, case-insensitive regex cannot use a normal B-tree index efficiently, so MongoDB scans. In a large collection that becomes a COLLSCAN. Prefer prefix search, a text index, or an Atlas Search index depending on the product need.
Why?
/^Rah/ can use an index. /rah/ and /rah/i generally cannot. Case-insensitive regex is especially costly. If the product needs 'contains, ignore case', that is a search problem, not a find() problem.
Interview tip
Do not offer 'add an index on name' as the fix for an unanchored regex. Name the real options: prefix, text, or search.
Common mistake
Adding a single-field index and expecting $regex: /rah/i to suddenly be an IXSCAN.
How did you do?
Cheat Sheet