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

สร้างดัชนีใหม่ (Rebuild Indexes) ใน MongoDB

ใช้คำสั่ง reIndex() เพื่อสร้างดัชนีทั้งหมดในคอลเลกชันใหม่ (Drop แล้วสร้างใหม่) ช่วยแก้ไขดัชนีเสียหายหรือปรับโครงสร้าง

สร้างดัชนีตัวอย่าง

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

คำสั่ง Rebuild Indexes

> db.demo42.reIndex({"StudentFirstName":1});

ผลลัพธ์ (แสดงดัชนีทั้งหมดหลัง Rebuild)

{
    "nIndexesWas" : 2,
    "nIndexes" : 2,
    "indexes" : [
        {"v" : 2, "key" : {"_id" : 1}, "name" : "_id_", "ns" : "web.demo42"},
        {"v" : 2, "key" : {"StudentFirstName" : 1}, "name" : "StudentFirstName_1", "ns" : "web.demo42"}
    ],
    "ok" : 1
}

คำเตือน:

  • reIndex() จะ Lock คอลเลกชัน (Block reads/writes) ระหว่างทำงาน
  • ไม่ควรใช้ใน Production ที่มี Traffic สูง
  • MongoDB 4.2+ ใช้ db.collection.reIndex() ไม่รับพารามิเตอร์ (Rebuild ทุกดัชนี)
  • สำหรับดัชนีเดียว ใช้ db.collection.dropIndex() แล้ว createIndex() แทน