Regex Queries
Regex Queries: free step-by-step lesson with examples, common mistakes, and interview tips — part of MongoDB Tutorial on Toolliyo Academy.
On this page
MongoDB Tutorial · Lesson 26 of 100
Regex Queries
Foundations & CRUD ✓ → Queries & Schema → Aggregation & Scale → Atlas & Projects
Queries & Schema · 2 — Design · ~6 min · MongoDB — Query Operators
What is this?
Regex queries match string patterns with $regex or /pattern/ syntax. Flags like i mean case-insensitive. Anchors ^ and $ bind start and end.
Why should you care?
Typeahead search for product names, filtering emails by domain, and finding SKUs by prefix all use regex — carefully, because leading-wildcard regex is slow.
See it live — copy this example
Open mongosh or MongoDB Compass, select database nosqlverse, then run the example. Change one field and run again.
db.products.insertMany([
{ name: "Sony WH-1000XM5", brand: "Sony" },
{ name: "sony portable speaker", brand: "Sony" },
{ name: "Boat Airdopes", brand: "Boat" }
])
db.products.find({ name: { $regex: /^sony/i } })
db.products.find({ name: /WH-1000/ })
db.products.find({ brand: { $regex: "oa", $options: "i" } })
Run Example »
Edit the code below and click Run to see the result in Toolliyo’s live editor.
What happened?
- First query finds names starting with sony ignoring case — both Sony products.
- Second finds the XM5 model substring.
- Third finds Boat via brand regex.
- Prefer prefix regex for index use when possible.
Practice next
- Seed the products.
- Run each regex find.
- Try { name: { $regex: "sony", $options: "i" } } without ^.
- Find emails ending with @gmail.com using $.
- Search tags with regex on an array field.
Remember
$regex matches text patterns. Use i for case-insensitive. Prefer prefix searches for performance.
Admin SKU prefix lookup
Warehouse staff type “WH-” and the tool runs /^WH-/i on sku.
Outcome: Matching headsets appear without a full catalog scan when indexed.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!