Introduction
Regex queries help you find text patterns in your data, like searching for words or parts of words easily.
db.collection.find({ field: { $regex: /pattern/, $options: 'i' } })db.users.find({ name: { $regex: /^A/ } })db.products.find({ description: { $regex: /fresh/i } })db.emails.find({ email: { $regex: /@gmail\.com$/ } })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' } })$regex operator do in a MongoDB query?$regex$regex operator is used to find text patterns inside string fields in MongoDB documents.$regex.$regex = pattern search [OK]name starts with 'A' using regex in MongoDB?^ means the start of the string, so ^A matches strings starting with 'A'.A$ matches strings ending with 'A', A* matches zero or more 'A's anywhere, and [A] matches any 'A' character anywhere.{"city": {"$regex": "^London$", "$options": "i"}} return?^London$ matches exactly 'London' from start to end. The option i makes it case-insensitive.title contains 'book' case-insensitive: {"title": {"$regex": "/book/i"}}$options field."/book/i" incorrectly includes slashes and option inside the string. It should be {"$regex": "book", "$options": "i"}.description field contains either 'cat' or 'dog' (case-insensitive). Which MongoDB query correctly uses regex to achieve this?cat|dog matches either 'cat' or 'dog'. The i option makes it case-insensitive.g which is not a valid MongoDB regex option. {"description": {"$regex": "cat|dog"}} misses the case-insensitive option.Pass the test and this pattern moves unknown