Để tìm các tài liệu mà trường chuỗi có 5 ký tự đầu tiên là chữ in hoa (A-Z), MongoDB sử dụng toán tử $regex với pattern /^[A-Z]{5}/. Dấu ^ đảm bảo khớp từ đầu chuỗi.
Tạo dữ liệu mẫu
> db.upperCaseFiveLetterDemo.insertOne({"StudentFullName":"JOHN Smith"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd7edef1a844af18acdffb2") }
> db.upperCaseFiveLetterDemo.insertOne({"StudentFullName":"SAM Williams"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd7ee011a844af18acdffb3") }
> db.upperCaseFiveLetterDemo.insertOne({"StudentFullName":"CAROL Taylor"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd7ee101a844af18acdffb4") }
> db.upperCaseFiveLetterDemo.insertOne({"StudentFullName":"Bob Taylor"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd7ee351a844af18acdffb5") }
> db.upperCaseFiveLetterDemo.insertOne({"StudentFullName":"DAVID Miller"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd7ee451a844af18acdffb6") }
Xem dữ liệu
> db.upperCaseFiveLetterDemo.find().pretty();
Đếm tài liệu có 5 ký tự đầu in hoa
> db.upperCaseFiveLetterDemo.find({StudentFullName: {$regex: /^[A-Z]{5}/}}).count();
Kết quả
2
Hiển thị các tài liệu khớp
> db.upperCaseFiveLetterDemo.find({StudentFullName: {$regex: /^[A-Z]{5}/}});
Giải thích Regex
^: Neo (anchor) đầu chuỗi
[A-Z]: Bất kỳ chữ cái in hoa nào từ A-Z
{5}: Chính xác 5 lần lặp lại
/^[A-Z]{5}/: Chuỗi bắt đầu bằng 5 chữ in hoa liên tiếp
Phân tích từng bản ghi
| Tên | 5 ký tự đầu | Khớp? |
| JOHN Smith | JOHN | ❌ (có space, chỉ 4 chữ) |
| SAM Williams | SAM W | ❌ (chỉ 3 chữ, có space) |
| CAROL Taylor | CAROL | ✅ (5 chữ in hoa) |
| Bob Taylor | Bob T | ❌ (có chữ thường) |
| DAVID Miller | DAVID | ✅ (5 chữ in hoa) |
Các pattern Regex hữu ích khác
| Pattern | Ý nghĩa |
/^[A-Z]+/ | Bắt đầu bằng 1+ chữ in hoa |
/^[A-Z]{3,5}/ | Bắt đầu bằng 3-5 chữ in hoa |
/^[A-Z][a-z]+/ | Bắt đầu bằng 1 chữ hoa, theo sau chữ thường |
/^[A-Z][a-z]* [A-Z][a-z]*/ | Tên riêng chuẩn: "John Smith" |
/^[A-Z]{2,}\s/ | Viết tắt in hoa + space: "USA " |
Tối ưu hiệu năng
- Regex có
^ (prefix) có thể dùng index
- Regex không có
^ hoặc có .* đầu → collection scan
- Tạo index:
db.upperCaseFiveLetterDemo.createIndex({StudentFullName: 1})
- Case insensitive:
{$regex: 'pattern', $options: 'i'}
Lưu ý
- MongoDB dùng PCRE (Perl Compatible Regular Expressions)
- Ký tự đặc biệt cần escape:
.*+?^${}()|[]\
- Đối với Unicode (tiếng Việt có dấu), dùng
$options: 'i' hoặc pattern Unicode