Chỉ mục cải thiện hiệu suất truy vấn đáng kể. Sử dụng phương thức createIndex(). Tạo collection với dữ liệu lồng nhau:
> db.demo702.createIndex({"details.id":1});
{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
> db.demo702.insertOne({
... "details": [
... { id:101, studentInfo: { "StudentName" : "Chris", "StudentAge" : 23 } },
... { id:102, studentInfo: { "StudentName" : "Robert", "StudentAge" : 20 } }
... ]
... });
{ "acknowledged" : true, "insertedId" : ObjectId("5ea6ea3b551299a9f98c93b3") }
Hiển thị dữ liệu:
> db.demo702.find().pretty();
{ "_id" : ObjectId("5ea6ea3b551299a9f98c93b3"), "details" : [ { "id" : 101, "studentInfo" : { "StudentName" : "Chris", "StudentAge" : 23 } }, { "id" : 102, "studentInfo" : { "StudentName" : "Robert", "StudentAge" : 20 } } ] }
Giải thích:
createIndex({"details.id":1})tạo chỉ mục tăng dần (1) trên trườngdetails.idtrong mảng- MongoDB tự động tạo chỉ mục cho
_id(numIndexesBefore: 1) - Sau khi tạo, có 2 chỉ mục (numIndexesAfter: 2)
Lưu ý: Chỉ mục trên trường trong mảng (multikey index) cho phép truy vấn nhanh các phần tử mảng.