Limit the number of documents in a collection in MongoDB?


To limit the number of documents in a collection, set capped − true. Set the size there itself. Let us create a collection with documents −

> 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")
}

Display all documents from a collection with the help of find() method −

> db.demo683.find();

This will produce the following output −

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

Updated on: 13-May-2020

352 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements