MongoDB รองรับ Full-Text Search ผ่าน Text Index และ Operator $text / $search เนื้อหานี้สาธิตการสร้าง Text Index บน Field StudentName และค้นหาคำว่า "John"
สร้าง Text Index และข้อมูลทดสอบ
> db.demo156.createIndex({"StudentName": "text"});
{ "createdCollectionAutomatically": true, "numIndexesBefore": 1, "numIndexesAfter": 2, "ok": 1 }
> db.demo156.insertOne({"StudentName": "Chris Brown"});
{ "acknowledged": true, "insertedId": ObjectId("5e3547e8fdf09dd6d08539e6") }
> db.demo156.insertOne({"StudentName": "John Doe"});
{ "acknowledged": true, "insertedId": ObjectId("5e3547f2fdf09dd6d08539e7") }
> db.demo156.insertOne({"StudentName": "John Smith"});
{ "acknowledged": true, "insertedId": ObjectId("5e3547f7fdf09dd6d08539e8") }
แสดงข้อมูลทั้งหมด
> db.demo156.find();
{
"_id": ObjectId("5e3547e8fdf09dd6d08539e6"),
"StudentName": "Chris Brown"
}
{
"_id": ObjectId("5e3547f2fdf09dd6d08539e7"),
"StudentName": "John Doe"
}
{
"_id": ObjectId("5e3547f7fdf09dd6d08539e8"),
"StudentName": "John Smith"
}
Query Text Search
> db.demo156.find({ $text: { $search: "John" } });
ผลลัพธ์ (Match 2 รายการ)
{
"_id": ObjectId("5e3547f7fdf09dd6d08539e8"),
"StudentName": "John Smith"
}
{
"_id": ObjectId("5e3547f2fdf09dd6d08539e7"),
"StudentName": "John Doe"
}
คำอธิบายและฟีเจอร์เพิ่มเติม
- Text Index: ต้องสร้างก่อนด้วย
createIndex({field: "text"})หรือ Compound:createIndex({name: "text", desc: "text"}) $search: รองรับ Multiple Terms (Space = OR), Phrase ("exact phrase"), Exclude (-term)- ตัวอย่าง:
{$search: "John Smith"}→ John OR Smith{$search: "\"John Smith\""}→ Exact Phrase "John Smith"{$search: "John -Smith"}→ มี John แต่ไม่มี Smith
- Score: ใช้
{ $meta: "textScore" }ใน Projection/Sort เพื่อเรียงตาม Relevance:db.demo156.find( { $text: { $search: "John" } }, { score: { $meta: "textScore" } } ).sort({ score: { $meta: "textScore" } }) - Case/Accent Insensitive โดย Default (ขึ้นกับ Language)
- Language: ระบุได้ใน Index
{ default_language: "thai" }หรือต่อ Query{ $language: "thai" } - ข้อจำกัด: Collection ใด Collection หนึ่ง มี Text Index ได้สูงสุด 1 Index