MongoDB: find documents matching regular expression
To find documents matching a regular expression in the MongoDB shell, use the
find() method with the $regex operator or a regex literal.Using a Regex Literal:
db.collectionName.find({ fieldName: /pattern/options });
Example: Find documents in the
users collection where the name field contains "john" (case-insensitive).
db.users.find({ name: /john/i });
Using the
$regex Operator:db.collectionName.find({ fieldName: { $regex: "pattern", $options: "options" } });
Example: Find documents in the
products collection where the description field contains "eco-friendly" (case-insensitive).db.products.find({ description: { $regex: "eco-friendly", $options: "i" } });
Explanation:
collectionName: The name of the collection to query.fieldName: The field within the documents to apply the regular expression to.pattern: The regular expression pattern to match.options: Optional flags to modify the regex behavior. Common options include:i: Case-insensitive matching.m: Multi-line matching.s: Allows the dot (.) to match newline characters.x: Ignores whitespace characters in the pattern unless escaped.