Khi MongoDB mất quá nhiều thời gian tìm bản ghi, hãy tạo **index** (chỉ mục) cho trường thường xuyên truy vấn. Cú pháp:
db.tenCollectionCuaBan.createIndex({tenTruongCuaBan: 1});
Có 3 cách tiếp cận tạo index tùy loại dữ liệu:
Cách 1: Index đơn giản (số 1 = tăng dần)
> db.takeLessTimeToSearchDemo.createIndex({"EmployeeName": 1});
{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
Cách 2: Text Index (tìm kiếm full-text)
> db.takeLessTimeToSearchDemo1.createIndex({"EmployeeName": "text"});
{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
Cách 3: Hashed Index (phân phối sharding)
> db.takeLessTimeToSearchDemo2.createIndex({"EmployeeName": "hashed"});
{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
Lưu ý: Index tăng tốc độ đọc nhưng làm chậm ghi (insert/update/delete) do phải cập nhật index.