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 regular expression to fetch record with specific name "John", instead of "john
To fetch records with a specific case-sensitive name using MongoDB regular expressions, use the exact pattern match syntax /searchWord/. By default, MongoDB regex is case-sensitive, so /John/ will match "John" but not "john".
Syntax
db.collection.find({"field": /exactPattern/});
Sample Data
db.demo221.insertMany([
{"Details": {"StudentName": "Chris", "StudentAge": 21}},
{"Details": {"StudentName": "John", "StudentAge": 20}},
{"Details": {"StudentName": "Bob", "StudentAge": 22}},
{"Details": {"StudentName": "john", "StudentAge": 24}}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e3ee15d03d395bdc213472b"),
ObjectId("5e3ee16503d395bdc213472c"),
ObjectId("5e3ee16b03d395bdc213472d"),
ObjectId("5e3ee17303d395bdc213472e")
]
}
Display All Documents
db.demo221.find();
{ "_id": ObjectId("5e3ee15d03d395bdc213472b"), "Details": { "StudentName": "Chris", "StudentAge": 21 } }
{ "_id": ObjectId("5e3ee16503d395bdc213472c"), "Details": { "StudentName": "John", "StudentAge": 20 } }
{ "_id": ObjectId("5e3ee16b03d395bdc213472d"), "Details": { "StudentName": "Bob", "StudentAge": 22 } }
{ "_id": ObjectId("5e3ee17303d395bdc213472e"), "Details": { "StudentName": "john", "StudentAge": 24 } }
Example: Case-Sensitive Search for "John"
To fetch only records with the exact case "John" (not "john") ?
db.demo221.find({"Details.StudentName": /John/});
{ "_id": ObjectId("5e3ee16503d395bdc213472c"), "Details": { "StudentName": "John", "StudentAge": 20 } }
Key Points
- MongoDB regex
/John/is case-sensitive by default - Matches only "John" but excludes "john", "JOHN", or other case variations
- Use
/john/iflag for case-insensitive matching if needed
Conclusion
MongoDB regular expressions provide precise case-sensitive matching using /pattern/ syntax. This allows filtering records with exact string cases, distinguishing between "John" and "john" effectively.
Advertisements
