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

Ý nghĩa trường max trong output MongoDB db.collection.stats()

Trường max trong db.collection.stats() chỉ xuất hiện trên **capped collection** (collection có giới hạn kích thước), chỉ định **số lượng tài liệu tối đa** cho phép.

Tạo capped collection với size 100 bytes, max 50 documents:

> db.createCollection("demo673", { capped: true, size: 100, max: 50 });
{ "ok" : 1 }

Thêm 3 tài liệu mẫu:

> db.demo673.insertOne({Name:"John",Age:23});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea3ec7304263e90dac943e8") }
> db.demo673.insertOne({Name:"Bob",Age:21});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea3ec7804263e90dac943e9") }
> db.demo673.insertOne({Name:"David",Age:20});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea3ec7f04263e90dac943ea") }

Hiển thị dữ liệu:

> db.demo673.find();

Kết quả:

Xem stats: db.demo673.stats() sẽ hiển thị:

{
  "ns" : "test.demo673",
  "capped" : true,
  "max" : 50,                    // ← trường max: tối đa 50 documents
  "size" : 100,                  // giới hạn dung lượng bytes
  "count" : 3,                   // số document hiện tại
  ...
}

Cơ chế capped collection:

  • Khi đạt size HOẶC max → tự động xóa document **CŨ NHẤT** (FIFO)
  • Không hỗ trợ delete, update tăng kích thước document
  • Phù hợp: log, cache, time-series, circular buffer
  • Thứ tự tự nhiên = thứ tự insert = thứ tự _id

Chuyển đổi: Không thể chuyển capped → normal. Tạo collection mới và copy data.