Regex queries in MongoDB - Time & Space Complexity
When using regex queries in MongoDB, it is important to understand how the search time changes as the data grows.
We want to know how the cost of searching with a pattern grows when there are more documents.
Analyze the time complexity of the following code snippet.
db.users.find({
name: { $regex: /^A/ }
})
.limit(10)
This query finds users whose names start with the letter 'A' and returns up to 10 results.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: MongoDB checks each document's 'name' field against the regex pattern.
- How many times: This check happens once for every document in the collection unless an index helps.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 regex checks |
| 100 | About 100 regex checks |
| 1000 | About 1000 regex checks |
Pattern observation: The number of regex checks grows directly with the number of documents.
Time Complexity: O(n)
This means the time to run the regex query grows linearly as the number of documents increases.
[X] Wrong: "Regex queries always use indexes and are very fast."
[OK] Correct: Regex queries often scan many documents unless the regex starts with a fixed prefix that matches an index.
Understanding how regex queries scale helps you explain database performance clearly and shows you know how to handle real data search challenges.
"What if we changed the regex to a pattern without a fixed prefix? How would the time complexity change?"
Practice
$regex operator do in a MongoDB query?Solution
Step 1: Understand the purpose of
The$regex$regexoperator is used to find text patterns inside string fields in MongoDB documents.Step 2: Compare with other operations
Sorting, updating, and deleting are different operations and do not use$regex.Final Answer:
It searches for documents where a field matches a text pattern. -> Option AQuick Check:
$regex= pattern search [OK]
- Confusing $regex with sorting or updating operations
- Thinking $regex modifies data instead of searching
- Assuming $regex works on non-string fields
name starts with 'A' using regex in MongoDB?Solution
Step 1: Understand regex anchors
The caret^means the start of the string, so^Amatches strings starting with 'A'.Step 2: Check other options
A$matches strings ending with 'A',A*matches zero or more 'A's anywhere, and[A]matches any 'A' character anywhere.Final Answer:
{"name": {"$regex": "^A"}} -> Option CQuick Check:
Start with 'A' = ^A [OK]
- Using $ instead of ^ to match start
- Misunderstanding * as 'starts with'
- Using character class [] without anchors
{"city": {"$regex": "^London$", "$options": "i"}} return?Solution
Step 1: Analyze the regex pattern and options
The pattern^London$matches exactly 'London' from start to end. The optionimakes it case-insensitive.Step 2: Check which documents match
"London" matches exactly, "london" matches ignoring case, but "Londonderry" does not match because it has extra characters.Final Answer:
[{"city": "London"}, {"city": "london"}] -> Option DQuick Check:
Exact match ignoring case = [{"city": "London"}, {"city": "london"}] [OK]
- Ignoring case option and missing lowercase match
- Assuming partial matches without anchors
- Confusing $regex with substring search
title contains 'book' case-insensitive: {"title": {"$regex": "/book/i"}}Solution
Step 1: Understand MongoDB regex syntax
In MongoDB, the regex pattern is a string without enclosing slashes. Options like 'i' go in a separate$optionsfield.Step 2: Identify the mistake in the query
The pattern"/book/i"incorrectly includes slashes and option inside the string. It should be{"$regex": "book", "$options": "i"}.Final Answer:
The regex pattern should not be enclosed in slashes. -> Option BQuick Check:
MongoDB regex no slashes, use $options [OK]
- Including slashes around regex pattern
- Putting options inside the pattern string
- Using wrong field names like $pattern
description field contains either 'cat' or 'dog' (case-insensitive). Which MongoDB query correctly uses regex to achieve this?Solution
Step 1: Understand regex alternation and options
The patterncat|dogmatches either 'cat' or 'dog'. Theioption makes it case-insensitive.Step 2: Evaluate each option
{"description": {"$regex": "cat|dog", "$options": "i"}} correctly uses the pattern and case-insensitive option. {"description": {"$regex": "[cat|dog]", "$options": "i"}} uses character class incorrectly, matching any single character 'c', 'a', 't', '|', 'd', 'o', or 'g'. {"description": {"$regex": "(cat|dog)", "$options": "g"}} usesgwhich is not a valid MongoDB regex option. {"description": {"$regex": "cat|dog"}} misses the case-insensitive option.Final Answer:
{"description": {"$regex": "cat|dog", "$options": "i"}} -> Option AQuick Check:
Use | for OR and 'i' for ignore case [OK]
- Using character classes [] instead of alternation |
- Using invalid regex options like 'g' in MongoDB
- Forgetting $options for case-insensitive search
Ready to prove it?
Pass the test and this pattern moves unknown
