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: Find name similar to Regular Expression input?
To find names similar to a regular expression input in MongoDB, use the $regex operator with the $options parameter for case-insensitive matching.
Syntax
db.collection.find({
"fieldName": {
$regex: "pattern",
$options: "i"
}
});
Sample Data
db.demo514.insertMany([
{"Information": {"FullName": "John Doe"}},
{"Information": {"FullName": "John Smith"}},
{"Information": {"FullName": "john doe"}},
{"Information": {"FullName": "Chris Brown"}}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e885116987b6e0e9d18f58c"),
ObjectId("5e88515e987b6e0e9d18f58d"),
ObjectId("5e885169987b6e0e9d18f58e"),
ObjectId("5e88516f987b6e0e9d18f58f")
]
}
Display All Documents
db.demo514.find();
{ "_id" : ObjectId("5e885116987b6e0e9d18f58c"), "Information" : { "FullName" : "John Doe" } }
{ "_id" : ObjectId("5e88515e987b6e0e9d18f58d"), "Information" : { "FullName" : "John Smith" } }
{ "_id" : ObjectId("5e885169987b6e0e9d18f58e"), "Information" : { "FullName" : "john doe" } }
{ "_id" : ObjectId("5e88516f987b6e0e9d18f58f"), "Information" : { "FullName" : "Chris Brown" } }
Example: Find Names Similar to "John Doe"
db.demo514.find({
"Information.FullName": {
$regex: "John Doe",
$options: "i"
}
});
{ "_id" : ObjectId("5e885116987b6e0e9d18f58c"), "Information" : { "FullName" : "John Doe" } }
{ "_id" : ObjectId("5e885169987b6e0e9d18f58e"), "Information" : { "FullName" : "john doe" } }
Key Points
- The
$options: "i"parameter makes the search case-insensitive - Use dot notation to access nested fields like
"Information.FullName" -
$regexsupports partial matching and pattern-based searches
Conclusion
The $regex operator with $options: "i" enables flexible, case-insensitive name matching in MongoDB. This approach is ideal for user search functionality where exact case matching isn't required.
Advertisements
