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

จะสร้างดัชนีซ้อนใน MongoDB ได้อย่างไร?


ในการสร้างดัชนีที่ซ้อนกันใน MongoDB คุณสามารถใช้ createIndex() หรือ sureIndex() ไวยากรณ์มีดังนี้ −

db.yourCollectionName.createIndex({"yourOuterFieldName.yourInnerFieldName.yourSecondInnerFieldName":1});

เพื่อให้เข้าใจไวยากรณ์ ให้เราสร้างคอลเลกชันด้วยเอกสาร แบบสอบถามเพื่อสร้างคอลเลกชันที่มีเอกสารมีดังนี้ -

> db.nestedIndexDemo.insertOne( ... { ... ... "CustomerId":101, ... "CustomerDetails":... { ... "CustomerListDetails":... { .. . "CustomerName":"Larry", ... "CustomerProjectName":"Project-1", ... "CustomerCountryName":"US" ... } ... } ... }... );{ "รับทราบ" :จริง "insertedId" :ObjectId("5c8fc565d3c9d04998abf010")}

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

> db.nestedIndexDemo.find().pretty();

ต่อไปนี้เป็นผลลัพธ์ -

{ "_id" :ObjectId("5c8fc565d3c9d04998abf010"), "CustomerId" :101, "CustomerDetails" :{ "CustomerListDetails" :{ "CustomerName" :"Larry", "CustomerProjectName" :"Project-1", " CustomerCountryName" :"US" } }}

นี่คือแบบสอบถามเพื่อสร้างดัชนีซ้อนใน MongoDB:

> db.nestedIndexDemo.createIndex({"CustomerDetails.CustomerListDetails.CustomerCountryName":1});{ "createdCollectionAutomatically" :false, "numIndexesBefore" :1, "numIndexesAfter" :2, "ok" :1} 

นี่คือแบบสอบถามเพื่อแสดงดัชนี -

> db.nestedIndexDemo.getIndexes();

ต่อไปนี้เป็นผลลัพธ์ -

[ { "v" :2, "key" :{ "_id" :1 }, "name" :"_id_", "ns" :"test.nestedIndexDemo" }, { "v" :2, " คีย์" :{ "CustomerDetails.CustomerListDetails.CustomerCountryName" :1 }, "name" :"CustomerDetails.CustomerListDetails.CustomerCountryName_1", "ns" :"test.nestedIndexDemo" }]