MongoDB Tutorial: Using Regex Operator for Pattern Matching
MongoDB comparison query operators such as $eq and $ne are useful for finding values that are equal to or not equal to a specific exact comparison value. When it's necessary to find values based on similarity instead, a pattern match is useful. To perform a pattern match in MongoDB, use { field : { $regex : "pattern" } }, where field
is the field you want to test and "pattern" is a regular expression pattern string that describes the general form of values that you want to match.
Patterns used with the $regex evaluation query operator can contain several special characters, or "metacharacters", that stand for something other than themselves.
While most characters in patterns match themselves, the following special characters are excaptions:
- asterisk (
*
), - plus sign (
+
), - question mark (
?
), - backslash (
\
), - period (
.
), - caret (
^
), - square brackets (
[
and]
), - dollar sign (
$
), - ampersand (
&
). - or sign (
|
).
\*
.
- The lack of special characters in a pattern matches any string that contains those characters, regardless of any characters comes before or after the pattern. For example, the pattern "a" matches any string that contains 'a' within the string.
- The '^' (caret) character matches strings that contain the pattern at the beginning of the string.
- The '$' (dollar sign) character matches strings that contain the pattern at the end of the string.
- The '.' (dot) character matches any single charater.
"d.g"
matches strings such as"big dog"
,"dig dug"
, and"[email protected]"
. Because '.' matches any single character, it matches itself and the pattern"d.g"
also matches the string"ed.gov"
.
The following table lists MySQL statements and the corresponding MongoDB statements.
MySQL | MongoDB | Method | ||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Create Connection | Create Client | require('mongodb').MongoClient | ||||||||||||||
Create Database | Create Connection & Database | connect() | ||||||||||||||
Create Table | Create Collection | createCollection() | ||||||||||||||
Insert Into | Insert | insertOne() | ||||||||||||||
Select From | Find | findOne() | ||||||||||||||
Where | Query | find() | ||||||||||||||
Comparison Query Operators =!= > < IN NOT IN | Comparison Query Operators $eq$ne $gt $lt $in $nin |
| ||||||||||||||
Logical Query Operators ANDOR NOT | Logical Query Operators $and$or $not $nor |
| ||||||||||||||
LIKE | $regex |
| ||||||||||||||
Order By | Sort | sort() | ||||||||||||||
Delete | Delete | deleteOne() | ||||||||||||||
Drop Table | Drop Collection | drop() | ||||||||||||||
Update | Update | updateOne() | ||||||||||||||
Limit | Limit | limit() | ||||||||||||||
Join | Join | aggregate([{ $lookup: }]) |