Phương thức explain("executionStats") cung cấp thông tin chi tiết về cách MongoDB thực thi truy vấn: sử dụng index nào, số tài liệu quét, thời gian, v.v. Rất quan trọng để tối ưu hiệu năng.
Dữ liệu mẫu
> db.demo157.insertOne({"Status":"Active"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e354fdffdf09dd6d08539fc") }
> db.demo157.insertOne({"Status":"InActive"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e354fe3fdf09dd6d08539fd") }
Xem dữ liệu
> db.demo157.find();
{ "_id" : ObjectId("5e354fdffdf09dd6d08539fc"), "Status" : "Active" }
{ "_id" : ObjectId("5e354fe3fdf09dd6d08539fd"), "Status" : "InActive" }
Phân tích truy vấn với explain
> db.demo157.find({Status: { $in: ['Active','InActive'] }}).explain("executionStats");
Kết quả chính (rút gọn)
{
"queryPlanner": {
"winningPlan": { "stage": "COLLSCAN", "filter": { "Status": { "$in": ["Active", "InActive"] } } }
},
"executionStats": {
"executionSuccess": true,
"nReturned": 2,
"executionTimeMillis": 18,
"totalDocsExamined": 2,
"executionStages": { "stage": "COLLSCAN", "nReturned": 2, "docsExamined": 2 }
},
"ok": 1
}
Giải thích các chỉ số quan trọng:
- stage: COLLSCAN – quét toàn bộ collection (chưa có index).
- totalDocsExamined – số tài liệu đọc (2).
- nReturned – số tài liệu trả về (2).
- executionTimeMillis – thời gian thực thi.
db.demo157.createIndex({Status: 1}) -> stage thành IXSCAN, totalDocsExamined giảm drasticaly.