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
Find which MongoDB document contains a specific string?
To find which document contains a specific string, use $regex along with find(). The regex operator performs pattern matching to locate documents containing the specified text substring.
Syntax
db.collection.find({
fieldName: { $regex: /pattern/flags }
});
Sample Data
db.demo597.insertMany([
{ "Name": "John Doe" },
{ "Name": "John Smith" },
{ "Name": "Chris Brown" },
{ "Name": "Adam Smith" }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e947ae3f5f1e70e134e2690"),
ObjectId("5e947ae8f5f1e70e134e2691"),
ObjectId("5e947aeff5f1e70e134e2692"),
ObjectId("5e947afff5f1e70e134e2693")
]
}
Display All Documents
db.demo597.find();
{ "_id": ObjectId("5e947ae3f5f1e70e134e2690"), "Name": "John Doe" }
{ "_id": ObjectId("5e947ae8f5f1e70e134e2691"), "Name": "John Smith" }
{ "_id": ObjectId("5e947aeff5f1e70e134e2692"), "Name": "Chris Brown" }
{ "_id": ObjectId("5e947afff5f1e70e134e2693"), "Name": "Adam Smith" }
Example: Find Documents Containing "smith"
Find all documents where the Name field contains "smith" (case-insensitive) ?
db.demo597.find({
Name: { $regex: /smith/i }
});
{ "_id": ObjectId("5e947ae8f5f1e70e134e2691"), "Name": "John Smith" }
{ "_id": ObjectId("5e947afff5f1e70e134e2693"), "Name": "Adam Smith" }
Key Points
- The
iflag makes the search case-insensitive. - Use
/pattern/for regex literals or"pattern"with$options. -
$regexperforms substring matching anywhere within the field value.
Conclusion
Use $regex with the i flag for case-insensitive string searching in MongoDB. This operator efficiently finds documents containing specific text patterns within field values.
Advertisements
