Computer >> Máy Tính >  >> Lập trình >> MongoDB

Làm cách nào để tạo một chỉ mục lồng nhau trong MongoDB?

Để tạo chỉ mục lồng nhau trong MongoDB, bạn có thể sử dụng createIndex () hoặc ensureIndex (). Cú pháp như sau -

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

Để hiểu cú pháp, chúng ta hãy tạo một bộ sưu tập với tài liệu. Truy vấn để tạo một bộ sưu tập với một tài liệu như sau -

> db.nestedIndexDemo.insertOne (... {... ... "CustomerId":101, ... "CustomerDetails":... {... "CustomerListDetails":... {.. . "CustomerName":"Larry", ... "CustomerProjectName":"Project-1", ... "CustomerCountryName":"US" ...} ...} ...} ...); { "inherit":true, "insertId":ObjectId ("5c8fc565d3c9d04998abf010")} 

Hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find (). Truy vấn như sau -

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

Sau đây là kết quả -

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

Đây là truy vấn để tạo chỉ mục lồng nhau trong MongoDB:

> db.nestedIndexDemo.createIndex ({"CustomerDetails.CustomerListDetails.CustomerCountryName":1}); {"createCollectionAutomatically":false, "numIndexesBefore":1, "numIndexesAfter":2, "ok":1} trước> 

Đây là truy vấn để hiển thị chỉ mục -

> db.nestedIndexDemo.getIndexes (); 

Sau đây là kết quả -

 [{"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 "}]