Hiểu operation "command" trong MongoDB Profiler
Khi bật profiler (db.setProfilingLevel(1)), các hoạt động được phân loại. "command" là loại operation cho các lệnh quản trị và aggregation.
Các operation thuộc loại "command"
count- Đếm tài liệufindAndModify- Tìm và sửa đổi (atomic)aggregate- Pipeline aggregationmapReduce- Map-Reduce (deprecated)distinct- Giá trị duy nhấtcreateIndexes,dropIndexes- Quản lý indexcollStats,dbStats- Thống kê
Ví dụ: count() được log là "command"
Tạo dữ liệu
> db.demo443.insertOne({ "Name": "Chris" });
> db.demo443.insertOne({ "Name": "Bob" });
> db.demo443.insertOne({ "Name": "David" });
Thực hiện count
> db.demo443.count();
3
Xem profiler log
> db.system.profile.find({ op: "command", "command.count": { $exists: true } }).pretty()
Kết quả profiler mẫu:
{
"op": "command",
"ns": "test.demo443",
"command": { "count": "demo443", "query": {} },
"keysExamined": 0,
"docsExamined": 0,
"numYields": 0,
"ok": 1
}
Phân biệt "query" vs "command"
| Loại | Ví dụ | Đặc điểm |
|---|---|---|
| query | find(), findOne() | Trả về cursor, có thể dùng index scan |
| command | count, aggregate, distinct | Trả về kết quả ngay, thường full-scan nếu không tối ưu |
| getmore | Duyệt cursor | Tiếp tục lấy batch tiếp theo |
Mẹo tối ưu
- Thay
count()bằngcountDocuments()(MongoDB 4.0+) để chính xác hơn với sharded cluster - Dùng
estimatedDocumentCount()cho đếm nhanh, không cần chính xác tuyệt đối - Pipeline
aggregate([{ $count: "total" }])tận dụng index tốt hơncount()cũ