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

Yes, you can limit the number of records in a MongoDB collection by creating a capped collection. Capped collections maintain insertion order and automatically remove the oldest documents when the collection reaches its maximum size or document limit.

Syntax

db.createCollection("collectionName", {
    capped: true,
    size: sizeInBytes,
    max: maxDocuments
});

Example: Create Collection with Document Limit

Let us create a collection that can hold a maximum of 3 documents ?

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

Insert Test Documents

Now let's insert more than 3 documents to see how the limit works ?

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

Verify Document Limit

Display all documents to confirm only the latest 3 records are retained ?

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

Key Points

  • Capped collections automatically remove oldest documents when limits are exceeded
  • Both size (in bytes) and max (document count) parameters are enforced
  • Documents maintain their natural insertion order
  • Useful for log files, session data, or any scenario requiring automatic cleanup

Conclusion

Capped collections provide an efficient way to limit records in MongoDB. When the maximum document count is reached, the oldest documents are automatically removed to maintain the specified limit.

Updated on: 2026-03-15T01:23:01+05:30

158 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements