Is there a way to limit the number of records in a certain MongoDB collection?


Yes, you can use capped parameter along with max size. Following is the syntax −

db.createCollection("yourCollectionName",{capped:true,size:yourSizeInBytes,max:howManyRecordsYouWant})

Let us first create a collection with capped:true −

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

We will now create a collection with documents −

> db.limitTheNumberOfRecordsDemo.insertOne({"ClientName":"James Brown"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd9e601b50a6c6dd317adad")
}
> db.limitTheNumberOfRecordsDemo.insertOne({"ClientName":"Sam Williams"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd9e60bb50a6c6dd317adae")
}
> db.limitTheNumberOfRecordsDemo.insertOne({"ClientName":"David Miller"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd9e612b50a6c6dd317adaf")
}
> db.limitTheNumberOfRecordsDemo.insertOne({"ClientName":"Carol Taylor"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd9e61ab50a6c6dd317adb0")
}
> db.limitTheNumberOfRecordsDemo.insertOne({"ClientName":"Adam Smith"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd9e649b50a6c6dd317adb1")
}
> db.limitTheNumberOfRecordsDemo.insertOne({"ClientName":"John Doe"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd9e64fb50a6c6dd317adb2")
}

Following is the query to display all documents from a collection with the help of find() method. Here you will get only 3 records from the above collection since we have set the capped with max size above −

> db.limitTheNumberOfRecordsDemo.find();

This will produce the following output −

{ "_id" : ObjectId("5cd9e61ab50a6c6dd317adb0"), "ClientName" : "Carol Taylor" }
{ "_id" : ObjectId("5cd9e649b50a6c6dd317adb1"), "ClientName" : "Adam Smith" }
{ "_id" : ObjectId("5cd9e64fb50a6c6dd317adb2"), "ClientName" : "John Doe" }
raja
Published on 13-Jun-2019 15:05:17
Advertisements