สร้าง Index บน Nested Field ด้วย Dot Notation
db.yourCollectionName.createIndex({"yourOuterFieldName.yourInnerFieldName.yourSecondInnerFieldName": 1});
สร้างข้อมูลตัวอย่าง (Nested 3 ชั้น)
> db.nestedIndexDemo.insertOne({
"CustomerId":101,
"CustomerDetails": {
"CustomerListDetails": {
"CustomerName":"Larry",
"CustomerProjectName": "Project-1",
"CustomerCountryName":"US"
}
}
});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8fc565d3c9d04998abf010") }
สร้าง Index บน CustomerCountryName (Nested 3 ชั้น)
> db.nestedIndexDemo.createIndex({"CustomerDetails.CustomerListDetails.CustomerCountryName": 1});
{ "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
แสดง Index ทั้งหมด
> db.nestedIndexDemo.getIndexes();
[
{ "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "test.nestedIndexDemo" },
{ "v" : 2, "key" : { "CustomerDetails.CustomerListDetails.CustomerCountryName" : 1 }, "name" : "CustomerDetails.CustomerListDetails.CustomerCountryName_1", "ns" : "test.nestedIndexDemo" }
]
Index ถูกสร้างบน Nested Field แบบ 3 ชั้น ใช้ Dot Notation ระบุ Path