0
0
MongoDBquery~20 mins

Regex queries in MongoDB - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Regex Query Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
2:00remaining
Find documents with names starting with 'A'
Given a collection users with documents containing a name field, which query returns all users whose names start with the letter 'A'?
MongoDB
db.users.find({ name: { $regex: '^A' } })
Adb.users.find({ name: { $regex: '^A' } })
Bdb.users.find({ name: { $regex: 'A$' } })
Cdb.users.find({ name: { $regex: 'A' } })
Ddb.users.find({ name: { $regex: '^a' } })
Attempts:
2 left
💡 Hint
Use ^ to match the start of the string.
query_result
intermediate
2:00remaining
Find documents with emails ending in '.com'
Which MongoDB query finds all documents in contacts collection where the email field ends with '.com'?
MongoDB
db.contacts.find({ email: { $regex: '\.com$' } })
Adb.contacts.find({ email: { $regex: '\.com' } })
Bdb.contacts.find({ email: { $regex: '^\.com' } })
Cdb.contacts.find({ email: { $regex: '.com' } })
Ddb.contacts.find({ email: { $regex: '\.com$' } })
Attempts:
2 left
💡 Hint
Use $ to match the end of the string and escape the dot.
📝 Syntax
advanced
2:00remaining
Identify the syntax error in regex query
Which of the following MongoDB queries has a syntax error and will fail to run?
A)} } '}4{d\}3{]Z-A[' :xeger$ { :edoc {(dnif.stcudorp.bd
Bdb.products.find({ code: { $regex: '[A-Z]{3}\d{4}' } })
Cb.products.find({ code: { $regex: '[A-Z]{3}\d{4}' } })
Ddb.products.find({ code: { $regex: '[A-Z]{3}\d{4}' } }
Attempts:
2 left
💡 Hint
Check for missing brackets or braces.
optimization
advanced
2:00remaining
Optimize regex query for case-insensitive search
You want to find all documents in employees where the department field contains the word 'sales' regardless of case. Which query is the most efficient and correct?
Adb.employees.find({ department: { $regex: '(?i)sales' } })
Bdb.employees.find({ department: { $regex: '[Ss][Aa][Ll][Ee][Ss]' } })
Cdb.employees.find({ department: { $regex: 'sales', $options: 'i' } })
Ddb.employees.find({ department: { $regex: 'sales' } })
Attempts:
2 left
💡 Hint
Use regex options for case-insensitivity.
🧠 Conceptual
expert
2:00remaining
Understanding regex anchoring in MongoDB queries
Consider the query db.logs.find({ message: { $regex: 'error' } }). Which statement best describes the behavior of this query?
AIt matches documents where 'message' contains the substring 'error' anywhere.
BIt matches documents where 'message' starts with 'error'.
CIt matches documents where 'message' ends with 'error'.
DIt matches documents where 'message' equals exactly 'error'.
Attempts:
2 left
💡 Hint
Think about what happens when no anchors are used in regex.