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
MongoDB query to search for string like "@email" in the field values
To search for strings containing "@email" in MongoDB field values, use regular expressions with the find() method. The i flag enables case-insensitive matching.
Syntax
db.collection.find({"fieldName": /pattern/flags});
Sample Data
Let us create a collection with documents −
db.demo727.insertMany([
{UserId: "John@email.com"},
{UserId: "John@yahoo.com"},
{UserId: "Chris@EMAIL.com"}
]);
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5eab375f43417811278f5898"),
ObjectId("5eab376043417811278f5899"),
ObjectId("5eab376143417811278f589a")
]
}
Display all documents from the collection −
db.demo727.find();
{ "_id" : ObjectId("5eab375f43417811278f5898"), "UserId" : "John@email.com" }
{ "_id" : ObjectId("5eab376043417811278f5899"), "UserId" : "John@yahoo.com" }
{ "_id" : ObjectId("5eab376143417811278f589a"), "UserId" : "Chris@EMAIL.com" }
Example: Search for "@email" Pattern
Following is the query to search for "@email" like string −
db.demo727.find({"UserId": /@email/i});
{ "_id" : ObjectId("5eab375f43417811278f5898"), "UserId" : "John@email.com" }
{ "_id" : ObjectId("5eab376143417811278f589a"), "UserId" : "Chris@EMAIL.com" }
Key Points
- The
/@email/ipattern matches any string containing "@email" (case-insensitive) - The
iflag makes the search case-insensitive, matching both "email" and "EMAIL" - Regular expressions in MongoDB use the format
/pattern/flags
Conclusion
Use MongoDB regular expressions with the i flag to perform case-insensitive string pattern matching. This approach effectively searches for partial string matches within field values.
Advertisements
