Để tối ưu hóa tìm kiếm văn bản (text search) trên trường chứa chuỗi dài, MongoDB hỗ trợ Text Index (từ phiên bản 2.4+). Đây là cách đúng đắn thay vì dùng index thường kết hợp $regex (chỉ hiệu quả với regex prefix như ^John).
1. Tạo Text Index
> db.demo46.createIndex({ "Name": "text" });
{ "createdCollectionAutomatically": true, "numIndexesBefore": 1, "numIndexesAfter": 2, "ok": 1 }
Lưu ý: ensureIndex() đã deprecated, dùng createIndex().
2. Chèn dữ liệu mẫu
> db.demo46.insertOne({ "Name": "John Smith" });
> db.demo46.insertOne({ "Name": "John Doe" });
> db.demo46.insertOne({ "Name": "Chris Brown" });
3. Tìm kiếm văn bản với $text
> db.demo46.find({ $text: { $search: "John" } });
4. Kết quả
{ "_id": ObjectId("..."), "Name": "John Doe" }
{ "_id": ObjectId("..."), "Name": "John Smith" }
So sánh với $regex:
$regex: /^John/: Chỉ dùng được index thường (B-tree) nếu là prefix, không hỗ trợ tìm từ giữa chuỗi, không phân tích ngôn ngữ.$text: Hỗ trợ tìm kiếm toàn văn bản (full-text), tách từ, bỏ qua stop words, xếp hạng độ liên quan (text score), hỗ trợ nhiều ngôn ngữ.
Mẹo: Dùng { $meta: "textScore" } trong projection/sort để sắp xếp theo độ liên quan.