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
Check if a field contains a string in MongoDB?
You can use the $regex operator to check if a field contains a string in MongoDB. This allows pattern matching and substring searches within document fields.
Syntax
db.collection.find({ "fieldName": { $regex: ".*searchString.*" } });
Sample Data
db.checkFieldContainsStringDemo.insertMany([
{ "Id": 1, "Name": "John" },
{ "Id": 2, "Name": "Johnson" },
{ "Id": 3, "Name": "Carol" },
{ "Id": 4, "Name": "Mike" },
{ "Id": 5, "Name": "Sam" },
{ "Id": 6, "Name": "Larry" }
]);
{
"acknowledged": true,
"insertedIds": {
"0": ObjectId("5c77d762fc4e719b197a12ed"),
"1": ObjectId("5c77d76bfc4e719b197a12ee"),
"2": ObjectId("5c77d774fc4e719b197a12ef"),
"3": ObjectId("5c77d77cfc4e719b197a12f0"),
"4": ObjectId("5c77d784fc4e719b197a12f1"),
"5": ObjectId("5c77d78cfc4e719b197a12f2")
}
}
Example 1: Find Documents Containing "John"
Search for names containing the substring "John" ?
db.checkFieldContainsStringDemo.find({ "Name": { $regex: ".*John.*" } });
{ "_id": ObjectId("5c77d762fc4e719b197a12ed"), "Id": 1, "Name": "John" }
{ "_id": ObjectId("5c77d76bfc4e719b197a12ee"), "Id": 2, "Name": "Johnson" }
Example 2: Case-Insensitive Search
Use the $options parameter for case-insensitive matching ?
db.checkFieldContainsStringDemo.find({
"Name": { $regex: "john", $options: "i" }
});
{ "_id": ObjectId("5c77d762fc4e719b197a12ed"), "Id": 1, "Name": "John" }
{ "_id": ObjectId("5c77d76bfc4e719b197a12ee"), "Id": 2, "Name": "Johnson" }
Key Points
-
.*pattern.*matches any string containing the pattern anywhere -
$options: "i"enables case-insensitive matching -
$regexsupports full regular expression syntax for complex patterns
Conclusion
The $regex operator provides flexible string matching in MongoDB. Use .*pattern.* for substring searches and add $options: "i" for case-insensitive queries to find documents containing specific text patterns.
Advertisements
