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

Giới hạn số lượng document trong collection MongoDB (Capped Collection)

Giải pháp: Capped Collection

MongoDB hỗ trợ Capped Collection - collection có kích thước cố định, tự động xóa document cũ nhất khi đầy (FIFO). Sử dụng tham số capped: true kèm size (dung lượng byte) và max (số document tối đa).

Cú pháp

db.createCollection("tenCollection", {capped: true, size: kichThuocByte, max: soLuongDoc})

Ví dụ minh họa

1. Tạo capped collection (max 3 document, size ~200KB)

> db.createCollection("limitTheNumberOfRecordsDemo", {capped:true, size:200024, max:3})
{ "ok" : 1 }

2. Thêm 6 document (vượt quá max=3)

> db.limitTheNumberOfRecordsDemo.insertOne({"ClientName":"James Brown"});
> db.limitTheNumberOfRecordsDemo.insertOne({"ClientName":"Sam Williams"});
> db.limitTheNumberOfRecordsDemo.insertOne({"ClientName":"David Miller"});
> db.limitTheNumberOfRecordsDemo.insertOne({"ClientName":"Carol Taylor"});
> db.limitTheNumberOfRecordsDemo.insertOne({"ClientName":"Adam Smith"});
> db.limitTheNumberOfRecordsDemo.insertOne({"ClientName":"John Doe"});

3. Xem kết quả (chỉ còn 3 document mới nhất)

> db.limitTheNumberOfRecordsDemo.find();
{ "_id" : ObjectId("5cd9e61ab50a6c6dd317adb0"), "ClientName" : "Carol Taylor" }
{ "_id" : ObjectId("5cd9e649b50a6c6dd317adb1"), "ClientName" : "Adam Smith" }
{ "_id" : ObjectId("5cd9e64fb50a6c6dd317adb2"), "ClientName" : "John Doe" }

3 document đầu (James Brown, Sam Williams, David Miller) đã bị tự động xóa theo FIFO.

Đặc điểm Capped Collection

  • Thứ tự chèn = thứ tự tự nhiên (natural order) - truy vấn nhanh không cần index.
  • Không thể xóa document riêng lẻ (chỉ drop cả collection).
  • Không thể cập nhật document làm tăng kích thước.
  • Phù hợp: log, cache, dữ liệu time-series rolling window.