Để thực hiện full-text search trong MongoDB, sử dụng $text kết hợp **text index**. Tạo collection với text index trên trường Name:
> db.demo654.createIndex({Name:"text"});
{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
> db.demo654.insertOne({"Name":"John Doe"});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea04e924deddd72997713c8") }
> db.demo654.insertOne({"Name":"Chris Brown"});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea04e9d4deddd72997713c9") }
> db.demo654.insertOne({"Name":"John Smith"});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea04ea54deddd72997713ca") }
> db.demo654.insertOne({"Name":"David Miller"});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea04eb24deddd72997713cb") }
Hiển thị dữ liệu:
> db.demo654.find();
Kết quả:
Tìm kiếm full-text từ khóa "John":
> db.demo654.find({ $text: { $search: "John" } } );Kết quả khớp 2 tài liệu chứa "John" (John Doe, John Smith):
Tính năng $text search:
- Tách từ (tokenize) theo ngôn ngữ, hỗ trợ stemming
- Không phân biệt chữ hoa/thường
- Hỗ trợ từ phủ định:
$search: "John -Doe"(có John, không có Doe) - Hỗ trợ cụm từ chính xác:
$search: "\"John Doe\"" - Sắp xếp theo độ liên quan:
.sort({ score: { $meta: "textScore" } })
Yêu cầu: Phải tạo **text index** trước (createIndex({field: "text"})). Một collection chỉ có **một** text index (có thể compound nhiều trường).