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

Giới hạn số lượng tài liệu trong collection MongoDB (Capped Collection)

Để giới hạn số lượng tài liệu trong một collection, hãy đặt capped: true khi tạo collection. Cần chỉ định size (dung lượng byte) và max (số lượng tài liệu tối đa).

Tạo capped collection:

> db.createCollection("demo683", { capped: true, size: 5 ,max:4} )
{ "ok" : 1 }

Chèn 6 tài liệu (vượt quá max=4):

> db.demo683.insertOne({Value:100});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea468afa7e81adc6a0b394e") }
> db.demo683.insertOne({Value:500});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea468b0a7e81adc6a0b394f") }
> db.demo683.insertOne({Value:1000});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea468b1a7e81adc6a0b3950") }
> db.demo683.insertOne({Value:400});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea468b2a7e81adc6a0b3951") }
> db.demo683.insertOne({Value:800});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea468b3a7e81adc6a0b3952") }
> db.demo683.insertOne({Value:700});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea468b4a7e81adc6a0b3953") }

Hiển thị tài liệu (chỉ còn 4 tài liệu mới nhất do cơ chế FIFO của capped collection):

> db.demo683.find();

Kết quả:

{ "_id" : ObjectId("5ea468b1a7e81adc6a0b3950"), "Value" : 1000 }
{ "_id" : ObjectId("5ea468b2a7e81adc6a0b3951"), "Value" : 400 }
{ "_id" : ObjectId("5ea468b3a7e81adc6a0b3952"), "Value" : 800 }
{ "_id" : ObjectId("5ea468b4a7e81adc6a0b3953"), "Value" : 700 }

Lưu ý: Các tài liệu đầu tiên (100, 500) đã bị tự động xóa để tuân thủ giới hạn max:4.