Steve Breese

A Chicago-based Full-stack JavaScript Developer

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 (|).
To match a special character, precede it with a backslash, like this \*.

  • 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.

MySQLMongoDBMethod
Create ConnectionCreate Clientrequire('mongodb').MongoClient
Create DatabaseCreate Connection & Databaseconnect()
Create TableCreate CollectioncreateCollection()
Insert IntoInsertinsertOne()
Select FromFindfindOne()
WhereQueryfind()
Comparison Query Operators
=
!=
>
<
IN
NOT IN
Comparison Query Operators
$eq
$ne
$gt
$lt
$in
$nin
MySQLMongoDB
SELECT * FROM Inventory WHERE qty = 20;db.inventory.find( { qty: { $eq: 20 } } )
SELECT * FROM Inventory WHERE qty != 20;db.inventory.find( { qty: { $ne: 20 } } )
UPDATE inventory SET price = 9.99 WHERE carrier.fee > 2db.inventory.update( { "carrier.fee": { $gt: 2 } }, { $set: { price: 9.99 } } )
SELECT * FROM inventory WHERE qty < 20;db.inventory.find( { qty: { $lt: 20 } } )
SELECT * FROM inventory WHERE qty IN (5, 15);db.inventory.find( { qty: { $in: [ 5, 15 ] } } )
SELECT * FROM inventory WHERE qty NOT IN (5, 15);db.inventory.find( { qty: { $nin: [ 5, 15 ] } } )
Logical Query Operators
AND
OR
NOT
Logical Query Operators
$and
$or
$not
$nor
MySQLMongoDB
SELECT * FROM inventory WHERE price > 19.99 AND category IN ('liquor', 'liqueur');db.inventory.find( { $and: [ { price: { $gt: 19.99 } }, { category: { $in: ['liquor', 'liqueur'] } } ] } )
SELECT * FROM inventory WHERE qty < 20 OR price = 10;db.inventory.find( { $or: [ { qty: { $lt: 20 } }, { price: 10 } ] } )
SELECT * FROM inventory WHERE NOT (price > 1.00);db.inventory.find( { price: { $not: { $gt: 1.99 } } } )
SELECT * FROM inventory WHERE price != 1.99 AND qty >= 20 AND sale = FALSE;db.inventory.find( { $nor: [ { price: 1.99 }, { qty: { $lt: 20 } }, { sale: true } ] } )
LIKE$regex
MySQLMongoDB
LIKE '%a%'{ "name": { "$regex": "a" }
LIKE 'A%'{ "name": { "$regex": "^A" }
LIKE '%e'{ "name": { "$regex": "e$" }
LIKE '%d_g%'{ "name": { "$regex": "d.g" }
Order BySortsort()
DeleteDeletedeleteOne()
Drop TableDrop Collectiondrop()
UpdateUpdateupdateOne()
LimitLimitlimit()
JoinJoinaggregate([{ $lookup: }])