Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to use $regex in MongoDB?
The $regex operator in MongoDB allows you to perform pattern matching on string fields using regular expressions. It's useful for text searches, filtering data based on patterns, and implementing case-insensitive queries.
Syntax
db.collection.find({
fieldName: {
$regex: "pattern",
$options: "options"
}
});
Common options include i for case-insensitive matching, m for multiline, and x for extended syntax.
Sample Data
db.regularExpressionDemo.insertMany([
{"UserName": "John"},
{"UserName": "JOHN"},
{"UserName": "john"},
{"UserName": "JoHn"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cdffc25bf3115999ed51210"),
ObjectId("5cdffc2ebf3115999ed51211"),
ObjectId("5cdffc35bf3115999ed51212"),
ObjectId("5cdffc3ebf3115999ed51213")
]
}
View Sample Data
db.regularExpressionDemo.find();
{ "_id": ObjectId("5cdffc25bf3115999ed51210"), "UserName": "John" }
{ "_id": ObjectId("5cdffc2ebf3115999ed51211"), "UserName": "JOHN" }
{ "_id": ObjectId("5cdffc35bf3115999ed51212"), "UserName": "john" }
{ "_id": ObjectId("5cdffc3ebf3115999ed51213"), "UserName": "JoHn" }
Example 1: Case-Sensitive Pattern Matching
db.regularExpressionDemo.find({'UserName': { $regex: 'JOHN'}});
{ "_id": ObjectId("5cdffc2ebf3115999ed51211"), "UserName": "JOHN" }
Example 2: Case-Insensitive Pattern Matching
db.regularExpressionDemo.find({'UserName': { $regex: 'JOHN', $options: 'i' }});
{ "_id": ObjectId("5cdffc25bf3115999ed51210"), "UserName": "John" }
{ "_id": ObjectId("5cdffc2ebf3115999ed51211"), "UserName": "JOHN" }
{ "_id": ObjectId("5cdffc35bf3115999ed51212"), "UserName": "john" }
{ "_id": ObjectId("5cdffc3ebf3115999ed51213"), "UserName": "JoHn" }
Common Patterns
-
^pattern- Matches strings starting with pattern -
pattern$- Matches strings ending with pattern -
.*pattern.*- Matches strings containing pattern anywhere -
[aeiou]- Matches any single vowel character
Conclusion
The $regex operator provides powerful pattern matching capabilities in MongoDB. Use the $options parameter with value 'i' for case-insensitive searches, making it ideal for flexible text filtering and search functionality.
Advertisements
