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

MongoDB explain() ดู Execution Stats เพื่อวิเคราะห์ Query Performance

Method explain() ใน MongoDB ใช้สำหรับดู Query Execution Plan และ Statistics เพื่อวิเคราะห์ Performance เนื้อหานี้สาธิตการใช้ explain("executionStats") กับ Query ที่มี $in Operator

ตัวอย่างข้อมูลทดสอบ

> db.demo157.insertOne({"Status":"Active"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e354fdffdf09dd6d08539fc") }

> db.demo157.insertOne({"Status":"InActive"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e354fe3fdf09dd6d08539fd") }

แสดงข้อมูลทั้งหมด

> db.demo157.find();
{
  "_id" : ObjectId("5e354fdffdf09dd6d08539fc"),
  "Status" : "Active"
}
{
  "_id" : ObjectId("5e354fe3fdf09dd6d08539fd"),
  "Status" : "InActive"
}

Query พร้อม explain()

> db.demo157.find({Status: { $in: ['Active','InActive'] }}).explain("executionStats");

ผลลัพธ์สำคัญ (Execution Stats)

{
  "queryPlanner": {
    "plannerVersion": 1,
    "namespace": "test.demo157",
    "indexFilterSet": false,
    "parsedQuery": {
      "Status": { "$in": [ "Active", "InActive" ] }
    },
    "winningPlan": {
      "stage": "COLLSCAN",
      "filter": { "Status": { "$in": [ "Active", "InActive" ] } },
      "direction": "forward"
    },
    "rejectedPlans": []
  },
  "executionStats": {
    "executionSuccess": true,
    "nReturned": 2,
    "executionTimeMillis": 18,
    "totalKeysExamined": 0,
    "totalDocsExamined": 2,
    "executionStages": {
      "stage": "COLLSCAN",
      "filter": { "Status": { "$in": [ "Active", "InActive" ] } },
      "nReturned": 2,
      "executionTimeMillisEstimate": 0,
      "works": 4,
      "advanced": 2,
      "needTime": 1,
      "needYield": 0,
      "isEOF": 1,
      "docsExamined": 2
    }
  },
  "serverInfo": { "host": "DESKTOP-QN2RB3H", "port": 27017, "version": "4.0.5" },
  "ok": 1
}

คำอธิบาย Metrics สำคัญ

Metricความหมาย
winningPlan.stageCOLLSCAN = Collection Scan (ไม่ใช้ Index), IXSCAN = Index Scan
totalDocsExaminedจำนวน Document ที่ต้องอ่าน (น้อย = ดี)
totalKeysExaminedจำนวน Index Key ที่ตรวจสอบ
executionTimeMillisเวลารัน Query (ms)
nReturnedจำนวน Document ที่คืนผล
worksหน่วยงานภายใน (Internal Work Units)

โหมด explain อื่นๆ

  • explain() / explain("queryPlanner"): แค่ Query Plan (ไม่รัน Query จริง)
  • explain("executionStats"): รัน Query จริง + Stats (Default แนะนำ)
  • explain("allPlansExecution"): รันทุก Candidate Plan + Stats

การเพิ่มประสิทธิภาพ

  • สร้าง Index: db.demo157.createIndex({Status: 1}) จะเปลี่ยน COLLSCAN → IXSCAN
  • ตรวจสอบ indexFilterSet และ rejectedPlans เพื่อดู Alternative Plans