MongoDB starts with a query
In this MongoDB article, users will learn how to start queries using $regex. It provides regular expression functionality for pattern matching strings in queries.
MongoDB starts querying using $regex
If you want to use $regex
, use one of the following syntaxes.
{ <field>: { $regex: /pattern/, $options: '<options>' } }
{ <field>: { $regex: 'pattern', $options: '<options>' } }
{ <field>: { $regex: /pattern/<options> } }
In MongoDB, users can also use regular expression objects (ie /pattern/) to specify regular expressions.
{ <field>: /pattern/<options> }
User can use <options>
regular expression with following .
Options | illustrate |
---|---|
i | Match case insensitively to upper and lower case. |
m | For strings with multi-line values, matches a pattern containing anchors (such as ^ at the beginning and $ at the end) at the beginning or end of each line. If the pattern has no anchors or the string value does not contain newlines (such as \n), the m option has no effect. |
x | All whitespace characters in the $regex pattern are ignored unless they are escaped or contained in a character class. It also ignores characters in the middle and includes an unescaped pound/hash (#) character followed by a newline, allowing you to add comments in complex patterns. Whitespace characters may not appear within special character sequences in the pattern; this only applies to data characters. The x option does not affect how VT characters are handled (i.e., code 11). It will require the $regex and $options syntax |
s | This allows the dot character (.) to match any character, including newline. Requires $regex and $options syntax |
The $regex operator does not support the global search modifier g.
$in Expression
Only the JavaScript regular expression object (ie /pattern/) can be used to incorporate regular expressions into $in query expressions. Consider the following example.
{ name: { $in: [ /^acme/i, /^ack/ ] } }
You cannot use $regex operator expressions in $in.
Implicit AND conditions for fields
Use the $regex operator to incorporate a regular expression into a comma-delimited list of query conditions for a field. Consider the following example.
{ name: { $regex: /acme.*corp/i, $nin: [ 'acmeblahcorp' ] } }
{ name: { $regex: /acme.*corp/, $options: 'i', $nin: [ 'acmeblahcorp' ] } }
{ name: { $regex: 'acme.*corp', $options: 'i', $nin: [ 'acmeblahcorp' ] } }
$regex operator with x and s
Users should use the $regex operator and the $options operator to use the x or s option. For example, to specify the i and s options, you must use $options.
{ name: { $regex: /acme.*corp/, $options: "si" } }
{ name: { $regex: 'acme.*corp', $options: "si" } }
PCRE and JavaScript
Users should use the $regex operator expression with the pattern as a string to leverage the features supported by PCRE in regular expression patterns that are not supported in JavaScript.
For example, you must use the $regex operator with the pattern as a string to use (?i) and (?-i) in the pattern to turn on case insensitivity for the rest of the pattern.
{ name: { $regex: '(?i)a(?-i)cme' } }
$regex and $not
Starting with version 4.0.7, the $not operator can perform a logical NOT operation on both:
-
Regular expression object (i.e. /pattern/)
For example:
db.inventory.find( { item: { $not: /^p.*/ } } )
-
$regex operator expression (as of MongoDB 4.0.7).
For example:
In versions 4.0.6 and earlier, you can use the $not operator with regular expression objects (that is, /pattern/), but not with $regex operator expressions.db.inventory.find( { item: { $not: { $regex: "^p.*" } } } ) db.inventory.find( { item: { $not: { $regex: /^p.*/ } } } )
If the field is indexed, MongoDB checks the regular expression against the values in the index, which is faster than a collection scan for a case-sensitive regular expression query.
More optimizations can be made if the regular expression has a prefix expression, which indicates that all possible matches start with the exact string. This enables MongoDB to create a range from the prefix and only match indexed values within that range.
If a regular expression begins with a caret (^) or left anchor (\A) followed by a string of simple symbols, it is called a prefix expression. For example, the regular expression /^abc.*/
will be optimized by matching only index values that begin with abc.
Furthermore, although /^a/
, , /^a.*/
and /^a.*$/
all match comparable strings, they perform differently.
All of these expressions will use a suitable index if one exists; however, this /^a.*/
is /^a.*$/
slower. The search can stop after matching the prefix /^a/
.
Case-insensitive regular expression queries cannot effectively utilize indexes. For example, the $regex implementation does not support collations, so case-insensitive indexes cannot be used.
example:
The following example uses a collection named products and the following documents.
{ "_id" : 100, "ski" : "abc123", "description" : "Single line description." },
{ "_id" : 101, "ski" : "abc789", "description" : "First line\nSecond line" },
{ "_id" : 102, "ski" : "xyz456", "description" : "Many spaces before line" },
{ "_id" : 103, "ski" : "xyz789", "description" : "Multiple\nline description" }
LIKE Statement
This example matches all documents where the ski field is similar to "%789".
db.products.find( { ski: { $regex: /789$/ } } )
The example is similar to the following SQL LIKE statement.
SELECT * FROM products
WHERE ski like "%789";
Case-insensitive regular expression matching
The following example uses the i option and performs a case-insensitive match on documents where the ski value begins with ABC.
db.products.find( { ski: { $regex: /^ABC/i } } )
The query matches the following documents.
{ "_id" : 100, "ski" : "abc123", "description" : "Single line description." }
{ "_id" : 101, "ski" : "abc789", "description" : "First line\nSecond line" }
Multi-line matching
The m option is used in the following example to match lines that begin with the letter S in a multiline string.
db.products.find( { description: { $regex: /^S/, $options: 'm' } } )
This query matches the following documents given below.
{ "_id" : 100, "ski" : "abc123", "description" : "Single line description." }
{ "_id" : 101, "ski" : "abc789", "description" : "First line\nSecond line" }
Without m
the option, the query will only match the following documents.
{ "_id" : 100, "ski" : "abc123", "description" : "Single line description." }
If the $regex pattern does not contain an anchor, the pattern is applied to the entire string, as shown in the following example.
db.products.find( { description: { $regex: /S/ } } )
Then, $regex
both documents will be matched.
{ "_id" : 100, "ski" : "abc123", "description" : "Single line description." }
{ "_id" : 101, "ski" : "abc789", "description" : "First line\nSecond line" }
. matches the dot character of a new line
The s option allows the dot character ( .
) to match all characters, including newlines, while the i option allows case-insensitive matching.
db.products.find( { description: { $regex: /m.*line/, $options: 'si' } } )
The query matches the following documents.
{ "_id" : 102, "ski" : "xyz456", "description" : "Many spaces before line" }
{ "_id" : 103, "ski" : "xyz789", "description" : "Multiple\nline description" }
Without the s option, the query will match only the following documents.
{ "_id" : 102, "ski" : "xyz456", "description" : "Many spaces before line" }
Whitespace in the pattern
In the matching pattern, the x option ignores spaces and comments represented by # and replaces them with n:..
var pattern = "abc #category code\n123 #item number"
db.products.find( { ski: { $regex: pattern, $options: "x" } } )
The query matches the following documents.
{ "_id" : 100, "ski" : "abc123", "description" : "Single line description." }
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
$ne operator in MongoDB
Publish Date:2025/04/11 Views:84 Category:MongoDB
-
This article will discuss how the $ne operator works in MongoDB. In addition, we will list its differences from the $not operator. $ne operator in MongoDB $ne is an operator in MongoDB that stands for not equal to. This will compare the val
MongoDB $Set Operator
Publish Date:2025/04/11 Views:159 Category:MongoDB
-
With the help of this article, you will learn how to use $set the operator to partially update objects in MongoDB so that the new object overlaps/merges with the existing object. The $set operator replaces the value of a field with a given
Difference between $push and $addToSet in MongoDB
Publish Date:2025/04/11 Views:63 Category:MongoDB
-
This article explains the operators in MongoDB. What is the purpose of $push and $addToSet operators. Furthermore, the difference between these two operators is given in the code snippet. This article discusses the following topics. Operato
Sort a collection by date in MongoDB
Publish Date:2025/04/11 Views:64 Category:MongoDB
-
In this MongoDB tutorial, the problem of sorting a collection in MongoDB is discussed. The different ways to sort a collection in the database are briefly explained. Using sort() function in MongoDB This problem is solved using the MongoDB
Counting records in MongoDB
Publish Date:2025/04/11 Views:146 Category:MongoDB
-
This article discusses operators in MongoDB, aggregation operators, and different ways to calculate the total number of records. Operations in MongoDB CRUD operations are a user interface concept that allows users to browse, search, and cha
Pretty printing in MongoDB
Publish Date:2025/04/11 Views:150 Category:MongoDB
-
This article will discuss how to use pretty printing in MongoDB to display formatted results. Pretty printing in MongoDB A cursor is an object that allows programmers in the Mongo world to iterate over documents in a Mongo collection. Altho
MongoDB Adding Elements to an Array
Publish Date:2025/04/11 Views:136 Category:MongoDB
-
This article will cover the various ways to add to an array in MongoDB. Adding to an array in MongoDB Use the $push operator to add values to an array The $push operator is one of the various array update operators provided by MongoDB
MongoDB Search by ID
Publish Date:2025/04/11 Views:131 Category:MongoDB
-
The following article provides an overview of MongoDB find by Id() method. MongoDB provides a find by Id() function which can retrieve documents matching a user id. To use search by Id() in MongoDB, you need to use the find() function. If n
Export all collections in MongoDB
Publish Date:2025/04/10 Views:188 Category:MongoDB
-
This MongoDB tutorial will show you how to export all MongoDB collections. Most databases and language frameworks allow you to export data. This makes the data useful to other programs, applications, or languages in various forms. CSV