$regex
The $regex operator allows you to perform regular expression matching on string fields. It is a powerful tool for searching and filtering documents based on complex patterns.
Parameters
-
regular expression: The regular expression pattern to match against the field. -
$options: (optional) Provides options to modify the search behavior, such as case-sensitivity, global matching, etc.
Example (MongoDB Shell)
The following example demonstrates the usage of the $regex operator to search for documents where the "name" field matches a specific pattern.
Create sample documents
db.users.insertMany([ { name: "John Doe" }, { name: "Jane Smith" }, { name: "Alice Johnson" }, { name: "Bob Williams" }, { name: "Charlie Davis" } ]);
Query example
db.users.find({ name: { $regex: /^A/ } })
Output
[
{ "_id" : ObjectId("..."), "name" : "Alice Johnson" }
]
This query will return all documents where the "name" field starts with the letter "A".
Code examples
To view a code example for using the $regex command, choose the tab for the language that you want to use: