0
0
MongoDBquery~5 mins

Regex queries in MongoDB

Choose your learning style9 modes available
Introduction
Regex queries help you find text patterns in your data, like searching for words or parts of words easily.
You want to find all users whose names start with 'A'.
You need to search for email addresses that contain 'gmail'.
You want to find products with descriptions that include the word 'fresh'.
You want to filter comments that mention a specific hashtag.
You want to find phone numbers that follow a certain pattern.
Syntax
MongoDB
db.collection.find({ field: { $regex: /pattern/, $options: 'i' } })
The pattern is a regular expression that describes the text you want to find.
The $options 'i' makes the search case-insensitive (ignores uppercase or lowercase).
Examples
Finds users whose name starts with the letter 'A'.
MongoDB
db.users.find({ name: { $regex: /^A/ } })
Finds products with 'fresh' in the description, ignoring case.
MongoDB
db.products.find({ description: { $regex: /fresh/i } })
Finds emails that end with '@gmail.com'.
MongoDB
db.emails.find({ email: { $regex: /@gmail\.com$/ } })
Sample Program
This inserts some users and then finds all users whose names start with 'A' or 'a'.
MongoDB
db.users.insertMany([
  { name: 'Alice' },
  { name: 'alex' },
  { name: 'Bob' },
  { name: 'Ann' },
  { name: 'Charlie' }
])

// Find users whose names start with 'A' (case-insensitive)
db.users.find({ name: { $regex: /^a/, $options: 'i' } })
OutputSuccess
Important Notes
Remember to escape special characters like '.' with a backslash (\\) in regex patterns.
Using regex can be slower on large collections if fields are not indexed properly.
Case-insensitive searches are helpful when you don't care about uppercase or lowercase letters.
Summary
Regex queries let you search text by patterns, not just exact matches.
Use $regex with patterns and optional $options like 'i' for case-insensitive search.
They are useful for flexible text searching in MongoDB collections.