Tìm kiếm văn bản với Regular Expression ($regex)
Sử dụng $regex để tìm document chứa chuỗi con, không phân biệt chữ hoa/thường, khớp mẫu phức tạp.
1. Dữ liệu mẫu
> db.demo469.insertOne({ StudentName: "John Doe" });
> db.demo469.insertOne({ StudentName: "Chris Brown" });
> db.demo469.insertOne({ StudentName: "John Smith" });
> db.demo469.insertOne({ StudentName: "Jace Doe" });
> db.demo469.insertOne({ StudentName: "David Miller" });
2. Tìm tên chứa "john" (case-insensitive)
> db.demo469.find({ 'StudentName': { '$regex': 'john', '$options': 'i' } });
3. Kết quả
{ "_id": ObjectId("5e80532fb0f3fa88e227906b"), "StudentName": "John Doe" }
{ "_id": ObjectId("5e805341b0f3fa88e227906d"), "StudentName": "John Smith" }
Các options quan trọng
| Option | Ý nghĩa |
i | Case-insensitive (không phân biệt hoa/thường) |
m | Multiline - ^ và $ khớp đầu/cuối dòng |
s | Dot matches newline (.) khớp xuống dòng) |
x | Extended - bỏ qua whitespace, cho phép comment |
Cú pháp thay thế (short form)
// Tương đương nhau:
db.demo469.find({ StudentName: /john/i });
db.demo469.find({ StudentName: { $regex: /john/i } });
db.demo469.find({ StudentName: { $regex: "john", $options: "i" } });
Các pattern hay dùng
// Bắt đầu bằng "John"
{ $regex: "^John", $options: "i" }
// Kết thúc bằng "Doe"
{ $regex: "Doe$", $options: "i" }
// Chứa "ohn" ở giữa
{ $regex: "ohn", $options: "i" }
// Từ hoàn chỉnh "John" (word boundary)
{ $regex: "\\bJohn\\b", $options: "i" }
// Phân cách bởi khoảng trắng
{ $regex: "\\sJohn\\s", $options: "i" }
⚠️ Hiệu suất & Index
- Chỉ dùng index khi pattern là prefix (^...) và không có option 'i'
/^john/i → KHÔNG dùng index (do option 'i')
/^John/ → CÓ dùng index (prefix, case-sensitive)
- Với tìm kiếm full-text → dùng Text Index (
db.coll.createIndex({ field: "text" }))
So sánh $regex vs Text Search
| Đặc điểm | $regex | Text Index ($text) |
| Hỗ trợ từ ngữ | Khó | ✅ Tự động tách từ, stem |
| Hiệu suất text lớn | Chậm (full scan) | ✅ Nhanh (inverted index) |
| Regex phức tạp | ✅ Hỗ trợ đầy đủ | ❌ Không hỗ trợ |
| Case-insensitive | Option 'i' | ✅ Mặc định |