Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

MongoDB Profiler: Operation "command" là gì?

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ệu
  • findAndModify - Tìm và sửa đổi (atomic)
  • aggregate - Pipeline aggregation
  • mapReduce - Map-Reduce (deprecated)
  • distinct - Giá trị duy nhất
  • createIndexes, dropIndexes - Quản lý index
  • collStats, 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ạiVí dụĐặc điểm
queryfind(), findOne()Trả về cursor, có thể dùng index scan
commandcount, aggregate, distinctTrả về kết quả ngay, thường full-scan nếu không tối ưu
getmoreDuyệt cursorTiếp tục lấy batch tiếp theo

Mẹo tối ưu

  • Thay count() bằng countDocuments() (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ơn count() cũ