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 regex to display records whose first five letters are uppercase?
To find MongoDB documents whose first five letters are uppercase, use the $regex operator with the pattern /^[A-Z]{5}/. The ^ ensures matching from the string beginning, and {5} specifies exactly five consecutive uppercase letters.
Syntax
db.collection.find({
fieldName: { $regex: /^[A-Z]{5}/ }
});
Sample Data
db.upperCaseFiveLetterDemo.insertMany([
{ "StudentFullName": "JOHN Smith" },
{ "StudentFullName": "SAM Williams" },
{ "StudentFullName": "CAROL Taylor" },
{ "StudentFullName": "Bob Taylor" },
{ "StudentFullName": "DAVID Miller" }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cd7edef1a844af18acdffb2"),
ObjectId("5cd7ee011a844af18acdffb3"),
ObjectId("5cd7ee101a844af18acdffb4"),
ObjectId("5cd7ee351a844af18acdffb5"),
ObjectId("5cd7ee451a844af18acdffb6")
]
}
Display All Documents
db.upperCaseFiveLetterDemo.find().pretty();
{
"_id": ObjectId("5cd7edef1a844af18acdffb2"),
"StudentFullName": "JOHN Smith"
}
{
"_id": ObjectId("5cd7ee011a844af18acdffb3"),
"StudentFullName": "SAM Williams"
}
{
"_id": ObjectId("5cd7ee101a844af18acdffb4"),
"StudentFullName": "CAROL Taylor"
}
{
"_id": ObjectId("5cd7ee351a844af18acdffb5"),
"StudentFullName": "Bob Taylor"
}
{
"_id": ObjectId("5cd7ee451a844af18acdffb6"),
"StudentFullName": "DAVID Miller"
}
Count Records with First Five Uppercase Letters
db.upperCaseFiveLetterDemo.find({
StudentFullName: { $regex: /^[A-Z]{5}/ }
}).count();
2
Display Matching Documents
db.upperCaseFiveLetterDemo.find({
StudentFullName: { $regex: /^[A-Z]{5}/ }
});
{ "_id": ObjectId("5cd7ee101a844af18acdffb4"), "StudentFullName": "CAROL Taylor" }
{ "_id": ObjectId("5cd7ee451a844af18acdffb6"), "StudentFullName": "DAVID Miller" }
Key Points
-
^anchor ensures matching from the beginning of the string -
[A-Z]{5}matches exactly 5 consecutive uppercase letters - Without
^, the regex would match any 5 uppercase letters anywhere in the string
Conclusion
Use $regex: /^[A-Z]{5}/ to find documents whose field values start with exactly five uppercase letters. The caret anchor ensures precise beginning-of-string matching for accurate results.
Advertisements
