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

ดัชนี MongoDB ไม่ทำงานเมื่อดำเนินการ $elemMatch?


เพื่อนำดัชนีไปใช้อย่างถูกต้องด้วย $elemMatch คุณต้องใช้แนวคิดของคำอธิบาย () ให้เราสร้างคอลเลกชันที่มีเอกสารก่อน -

> db.workingOfIndexesDemo.createIndex({"Information.StudentDetails.StudentName":1},{ กระจัดกระจาย:จริง พื้นหลัง:จริง } );{ "createdCollectionAutomatically" :จริง "numIndexesBefore" :1 "numIndexesAfter" :2, "ตกลง" :1}> db.workingOfIndexesDemo.insertOne({"Information":{"StudentDetails":{"StudentName":"Chris"}}});{ "acknowledged" :true, "insertedId" :ObjectId ("5e06f94825ddae1f53b621f7")}> db.workingOfIndexesDemo.insertOne({"Information":{"StudentDetails":{"StudentName":"David"}}});{ "acknowledged" :true, "insertedId" :ObjectId(" 5e06f94f25ddae1f53b621f8")}> db.workingOfIndexesDemo.insertOne({"Information":{"StudentDetails":{"StudentName":"Mike"}}});{ "acknowledged" :true, "insertedId" :ObjectId325("dde106f"953b95b )}

ต่อไปนี้เป็นแบบสอบถามเพื่อแสดงเอกสารทั้งหมดจากคอลเลกชันโดยใช้วิธี find() -

> db.workingOfIndexesDemo.find();

สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -

{ "_id" :ObjectId("5e06f94825ddae1f53b621f7"), "Information" :{ "StudentDetails" :{ "StudentName" :"Chris" } } } }{ "_id" :ObjectId("5e06f94f25dfa8f") :{ "StudentDetails" :{ "StudentName" :"David" } } } }{ "_id" :ObjectId("5e06f95325ddae1f53b621f9"), "Information" :{ "StudentDetails" :{ "StudentName" :"Mike}<} } } /pre> 

ต่อไปนี้เป็นแบบสอบถามเพื่อดำเนินการ $elemMatch พร้อมคำอธิบาย () ใน MongoDB -

> db.workingOfIndexesDemo.find({"Information.StudentDetails":{ $elemMatch:{ "StudentName" :"David"} } } ).explain();

สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -

{ "queryPlanner" :{ "plannerVersion" :1, "namespace" :"test.workingOfIndexesDemo", "indexFilterSet" :false, "parsedQuery" :{ "Information.StudentDetails" :{ "$elemMatch" :{ " StudentName" :{ "$eq" :"David" } } } }, "winningPlan" :{ "stage" :"FETCH", "filter" :{ "Information.StudentDetails" :{ "$elemMatch" :{ "StudentName" " :{ "$eq" :"David" } } } }, "inputStage" :{ "stage" :"IXSCAN", "keyPattern" :{ "Information.StudentDetails.StudentName" :1 }, "indexName" :" Information.StudentDetails.StudentName_1", "isMultiKey" :เท็จ "multiKeyPaths" :{ "Information.StudentDetails. StudentName" :[ ] }, "isUnique" :false, "isSparse" :true, "isPartial" :false, "indexVersion" :2, "direction" :"forward", "indexBounds" :{ "Information.StudentDetails.StudentName" " :[ "[\"David\", \"David\"]" ] } } }, "rejectedPlans" :[ ] }, "serverInfo" :{ "host" :"DESKTOP-QN2RB3H", "port" :27017 "เวอร์ชัน" :"4.0.5" "gitVersion" :"3739429dd92b92d1b0ab120911a23d50bf03c412" } "ตกลง" :1}