Bird
Raised Fist0
MongoDBquery~10 mins

Regex queries in MongoDB - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Regex queries in MongoDB
Start Query
↓
Specify Collection
↓
Define Regex Pattern
↓
Run Query with Regex
↓
Match Documents Found?
No→Return Empty Result
Yes↓
Return Matched Documents
↓
End Query
The query starts by selecting a collection, then defines a regex pattern to search text fields. It runs the query, checks if documents match, and returns those matches or an empty result.
Execution Sample
MongoDB
db.users.find({name: {$regex: '^A', $options: 'i'}})
Finds all users whose name starts with 'A', case-insensitive.
Execution Table
StepActionRegex PatternDocument CheckedMatch ResultOutput
1Start query on 'users' collection^AN/AN/ANo output yet
2Check document 1: {name: 'Alice'}^A{name: 'Alice'}MatchesInclude document 1
3Check document 2: {name: 'bob'}^A{name: 'bob'}No matchExclude document 2
4Check document 3: {name: 'anna'}^A{name: 'anna'}Matches (case-insensitive)Include document 3
5Check document 4: {name: 'Mark'}^A{name: 'Mark'}No matchExclude document 4
6All documents checked^AN/AN/AReturn matched documents: 1 and 3
💡 All documents checked; query returns documents matching regex '^A' case-insensitive.
Variable Tracker
VariableStartAfter Doc 1After Doc 2After Doc 3After Doc 4Final
matchedDocuments[][{name: 'Alice'}][{name: 'Alice'}][{name: 'Alice'}, {name: 'anna'}][{name: 'Alice'}, {name: 'anna'}][{name: 'Alice'}, {name: 'anna'}]
Key Moments - 2 Insights
Why does 'anna' match the regex '^A' even though it starts with lowercase 'a'?
Because the regex uses the 'i' option for case-insensitive matching, as shown in execution_table row 4.
What happens if no documents match the regex?
The query returns an empty result set, as explained in the exit_note and the 'No match' rows in the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, which document is included after checking document 3?
AOnly {name: 'Alice'}
BOnly {name: 'anna'}
CBoth {name: 'Alice'} and {name: 'anna'}
DNo documents included yet
💡 Hint
Check the 'Output' column at step 4 in the execution_table.
At which step does the query decide to exclude {name: 'bob'}?
AStep 3
BStep 4
CStep 2
DStep 5
💡 Hint
Look at the 'Match Result' column for document 2 in the execution_table.
If the regex pattern changed to '^M', which document would be included?
A{name: 'Alice'}
B{name: 'Mark'}
C{name: 'anna'}
DNo documents
💡 Hint
Refer to the 'Document Checked' and 'Match Result' columns in the execution_table.
Concept Snapshot
MongoDB regex queries use {$regex: pattern, $options: flags} inside find().
Pattern matches text fields; options like 'i' make it case-insensitive.
Query returns documents where the field matches the regex.
Example: {name: {$regex: '^A', $options: 'i'}} finds names starting with 'A' or 'a'.
Full Transcript
This visual execution shows how MongoDB regex queries work step-by-step. The query starts by selecting the 'users' collection and defining a regex pattern '^A' with the 'i' option for case-insensitive matching. Each document is checked against this pattern. Documents like {name: 'Alice'} and {name: 'anna'} match and are included in the results, while others like {name: 'bob'} and {name: 'Mark'} do not match and are excluded. The variable tracker shows how matchedDocuments grows as matching documents are found. Key moments clarify why case-insensitivity matters and what happens if no matches occur. The quiz tests understanding of which documents match and when exclusions happen. This helps beginners see exactly how regex queries filter documents in MongoDB.

Practice

(1/5)
1. What does the $regex operator do in a MongoDB query?
easy
A. It searches for documents where a field matches a text pattern.
B. It sorts documents in ascending order.
C. It updates documents with new values.
D. It deletes documents matching a condition.

Solution

  1. Step 1: Understand the purpose of $regex

    The $regex operator is used to find text patterns inside string fields in MongoDB documents.
  2. Step 2: Compare with other operations

    Sorting, updating, and deleting are different operations and do not use $regex.
  3. Final Answer:

    It searches for documents where a field matches a text pattern. -> Option A
  4. Quick Check:

    $regex = pattern search [OK]
Hint: Remember: $regex means 'match pattern' in text fields [OK]
Common Mistakes:
  • Confusing $regex with sorting or updating operations
  • Thinking $regex modifies data instead of searching
  • Assuming $regex works on non-string fields
2. Which of the following is the correct syntax to find documents where the field name starts with 'A' using regex in MongoDB?
easy
A. {"name": {"$regex": "A$"}}
B. {"name": {"$regex": "A*"}}
C. {"name": {"$regex": "^A"}}
D. {"name": {"$regex": "[A]"}}

Solution

  1. Step 1: Understand regex anchors

    The caret ^ means the start of the string, so ^A matches strings starting with 'A'.
  2. 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.
  3. Final Answer:

    {"name": {"$regex": "^A"}} -> Option C
  4. Quick Check:

    Start with 'A' = ^A [OK]
Hint: Use ^ at start of pattern to match beginning of string [OK]
Common Mistakes:
  • Using $ instead of ^ to match start
  • Misunderstanding * as 'starts with'
  • Using character class [] without anchors
3. Given the collection documents: [{"city": "London"}, {"city": "london"}, {"city": "Londonderry"}], what will the query {"city": {"$regex": "^London$", "$options": "i"}} return?
medium
A. []
B. [{"city": "London"}]
C. [{"city": "Londonderry"}]
D. [{"city": "London"}, {"city": "london"}]

Solution

  1. Step 1: Analyze the regex pattern and options

    The pattern ^London$ matches exactly 'London' from start to end. The option i makes it case-insensitive.
  2. Step 2: Check which documents match

    "London" matches exactly, "london" matches ignoring case, but "Londonderry" does not match because it has extra characters.
  3. Final Answer:

    [{"city": "London"}, {"city": "london"}] -> Option D
  4. Quick Check:

    Exact match ignoring case = [{"city": "London"}, {"city": "london"}] [OK]
Hint: Use ^ and $ for exact match; 'i' option ignores case [OK]
Common Mistakes:
  • Ignoring case option and missing lowercase match
  • Assuming partial matches without anchors
  • Confusing $regex with substring search
4. Identify the error in this MongoDB query to find documents where title contains 'book' case-insensitive: {"title": {"$regex": "/book/i"}}
medium
A. The $regex operator cannot be used with strings.
B. The regex pattern should not be enclosed in slashes.
C. The $options field is missing.
D. The field name should be $pattern, not $regex.

Solution

  1. Step 1: Understand MongoDB regex syntax

    In MongoDB, the regex pattern is a string without enclosing slashes. Options like 'i' go in a separate $options field.
  2. 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"}.
  3. Final Answer:

    The regex pattern should not be enclosed in slashes. -> Option B
  4. Quick Check:

    MongoDB regex no slashes, use $options [OK]
Hint: Do not use /slashes/ in MongoDB regex patterns [OK]
Common Mistakes:
  • Including slashes around regex pattern
  • Putting options inside the pattern string
  • Using wrong field names like $pattern
5. You want to find all documents where the description field contains either 'cat' or 'dog' (case-insensitive). Which MongoDB query correctly uses regex to achieve this?
hard
A. {"description": {"$regex": "cat|dog", "$options": "i"}}
B. {"description": {"$regex": "[cat|dog]", "$options": "i"}}
C. {"description": {"$regex": "(cat|dog)", "$options": "g"}}
D. {"description": {"$regex": "cat|dog"}}

Solution

  1. Step 1: Understand regex alternation and options

    The pattern cat|dog matches either 'cat' or 'dog'. The i option makes it case-insensitive.
  2. 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"}} uses g which is not a valid MongoDB regex option. {"description": {"$regex": "cat|dog"}} misses the case-insensitive option.
  3. Final Answer:

    {"description": {"$regex": "cat|dog", "$options": "i"}} -> Option A
  4. Quick Check:

    Use | for OR and 'i' for ignore case [OK]
Hint: Use | inside regex and $options: 'i' for case-insensitive [OK]
Common Mistakes:
  • Using character classes [] instead of alternation |
  • Using invalid regex options like 'g' in MongoDB
  • Forgetting $options for case-insensitive search
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard