Collection में documents की number limit करने के लिए capped: true set करें। Size भी वहीँ set करें।
Capped Collection बनाना
> db.createCollection( "demo683", { capped: true, size: 5 ,max:4} )
{ "ok" : 1 }
> 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") }
Documents Display करना
> db.demo683.find();
Output (केवल last 4 documents क्योंकि max:4 set है):
{ "_id" : ObjectId("5ea468b1a7e81adc6a0b3950"), "Value" : 1000 }
{ "_id" : ObjectId("5ea468b2a7e81adc6a0b3951"), "Value" : 400 }
{ "_id" : ObjectId("5ea468b3a7e81adc6a0b3952"), "Value" : 800 }
{ "_id" : ObjectId("5ea468b4a7e81adc6a0b3953"), "Value" : 700 }
व्याख्या: Capped collection fixed-size collection होता है जो insertion order के आधार पर documents को maintain करता है। जब maximum size या document count reach हो जाता है, तो oldest documents automatically remove हो जाते हैं। यहाँ size: 5 (bytes में) और max: 4 (maximum documents) set किया गया है।