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
Using a regex with text search in MongoDB
To filter records using Regular Expression in MongoDB, use the $regex operator. This allows you to search for documents that match specific text patterns within string fields.
Syntax
db.collection.find({
"fieldName": {
$regex: /pattern/,
$options: "flags"
}
});
Sample Data
Let's create a collection with sample documents ?
db.demo19.insertMany([
{"Values": "4321GH"},
{"Values": "12321_Carol"},
{"Values": "8765Mike"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e1389b955d0fc6657d21f0f"),
ObjectId("5e1389c755d0fc6657d21f10"),
ObjectId("5e1389d355d0fc6657d21f11")
]
}
Example: Using $regex with OR Pattern
Search for documents containing either "4321" or "8765" in the Values field ?
db.demo19.find({
Values: {
$regex: /4321|8765/,
$options: 'i'
}
});
{ "_id": ObjectId("5e1389b955d0fc6657d21f0f"), "Values": "4321GH" }
{ "_id": ObjectId("5e1389d355d0fc6657d21f11"), "Values": "8765Mike" }
Key Points
- The
|operator in regex creates an OR condition between patterns -
$options: 'i'makes the search case-insensitive - Use forward slashes
/pattern/for regex literals or string format with escaped characters
Conclusion
The $regex operator enables powerful pattern matching in MongoDB queries. Use the pipe (|) symbol for OR conditions and $options for additional regex flags like case-insensitive matching.
Advertisements
