Khi truy vấn chậm, hãy tạo index trên trường thường được tìm kiếm. Tạo collection với index:
> db.decreasetimeusingindex.createIndex({"StudentName":1});
{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
> db.decreasetimeusingindex.insertOne({"StudentName":"John Smith","StudentAge":21});
{ "acknowledged" : true, "insertedId" : ObjectId("5e03960af5e889d7a51994ff") }
> db.decreasetimeusingindex.insertOne({"StudentName":"John Doe","StudentAge":24});
{ "acknowledged" : true, "insertedId" : ObjectId("5e039611f5e889d7a5199500") }
> db.decreasetimeusingindex.insertOne({"StudentName":"Adam Smith","StudentAge":22});
{ "acknowledged" : true, "insertedId" : ObjectId("5e03961df5e889d7a5199501") }
Hiển thị tài liệu:
> db.decreasetimeusingindex.find().pretty();
Tìm kiếm chính xác bằng index:
> db.decreasetimeusingindex.find({"StudentName":"Adam Smith"});Giải thích: Index trên StudentName cho phép MongoDB dùng
IXSCAN(index scan) thay vìCOLLSCAN(collection scan), tăng tốc độ đáng kể trên dữ liệu lớn. Kiểm tra bằng.explain()để thấy "winningPlan.stage": "IXSCAN".