Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

วิธีแก้ไขเมื่อ MongoDB ค้นหาเรคคอร์ดช้าเกินไป

เมื่อ MongoDB ค้นหาเรคคอร์ดช้า ให้สร้าง ดัชนี (Index) บนฟิลด์ที่ใช้ค้นหาบ่อย ไวยากรณ์พื้นฐาน:

db.yourCollectionName.createIndex({yourFieldName: 1});

ตัวอย่างการสร้างดัชนีแบบต่างๆ:

วิธีที่ 1: ดัชนีแบบ Single Field (Ascending)

> db.takeLessTimeToSearchDemo.createIndex({"EmployeeName":1});
{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }

วิธีที่ 2: ดัชนีข้อความ (Text Index) สำหรับค้นหาข้อความเต็ม

> db.takeLessTimeToSearchDemo1.createIndex({"EmployeeName":"text"});
{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }

วิธีที่ 3: ดัชนีแฮช (Hashed Index) สำหรับ Sharding

> db.takeLessTimeToSearchDemo2.createIndex({"EmployeeName":"hashed"});
{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }

ประเภทดัชนีหลัก:

  • 1 / -1 - Single field index (ascending/descending)
  • "text" - Text index สำหรับ full-text search
  • "hashed" - Hashed index สำหรับ shard key
  • {field1: 1, field2: -1} - Compound index
  • {location: "2dsphere"} - Geospatial index

แนวทางปฏิบัติที่ดี: ใช้ explain() ตรวจสอบแผนการคิวรี่ ก่อนและหลังสร้างดัชนี เพื่อยืนยันว่าดัชนีถูกใช้งานจริง