$regex — MongoDB Technical Interview Questions & Answers

Pattern-matching string fields with regular expressions.

$regex

  • Simple meaning: $regex matches a string pattern (like SQL LIKE, but with regex).
  • How to use: db.students.find({ name: { $regex: /^As/ } }) names starting with As. Options: { $regex: "asha", $options: "i" } for ignore case.
  • Try this: find names starting with A.
  • Common mistake: leading wildcard regex on a huge collection with no index — slow. Prefer prefix /^A/ when you can.
  • Interview tip: Show /^prefix/ and mention indexes + case-insensitive option.

Technical Interview Tip: One prefix regex on name.

Code Examples for $regex

$regex — working example

db.users.find({
  email: { $regex: /@example\.com$/i }
})

$regex matches string fields with a regular expression (often with $options: 'i').

How to Explain $regex to an Interviewer

How do you find names starting with A?

{ name: { $regex: /^A/ } }