MongoDB query to insert but limit the total records

To insert documents while limiting the total records in a MongoDB collection, use capped collections with the capped: true option and set the max parameter to define the maximum number of documents.

Syntax

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

Create Capped Collection

Let us create a capped collection that allows a maximum of 4 documents ?

db.createCollection("demo297", {capped: true, size: 4, max: 4});
{ "ok" : 1 }

Insert Documents

Now insert 5 documents to see how the collection maintains the limit ?

db.demo297.insertMany([
    {"Name": "Chris"},
    {"Name": "Bob"},
    {"Name": "Mike"},
    {"Name": "Sam"},
    {"Name": "John"}
]);
{
    "acknowledged" : true,
    "insertedIds" : [
        ObjectId("5e4d54385d93261e4bc9ea43"),
        ObjectId("5e4d543e5d93261e4bc9ea44"),
        ObjectId("5e4d543e5d93261e4bc9ea45"),
        ObjectId("5e4d543f5d93261e4bc9ea46"),
        ObjectId("5e4d54405d93261e4bc9ea47")
    ]
}

Verify Result

Display all documents to see which records remain ?

db.demo297.find();
{ "_id" : ObjectId("5e4d543e5d93261e4bc9ea44"), "Name" : "Bob" }
{ "_id" : ObjectId("5e4d543e5d93261e4bc9ea45"), "Name" : "Mike" }
{ "_id" : ObjectId("5e4d543f5d93261e4bc9ea46"), "Name" : "Sam" }
{ "_id" : ObjectId("5e4d54405d93261e4bc9ea47"), "Name" : "John" }

Key Points

  • Capped collections automatically remove the oldest documents when the limit is exceeded.
  • The size parameter sets storage space in bytes (minimum 4096 bytes).
  • The max parameter limits the total number of documents.
  • Documents maintain insertion order and cannot be updated to increase size.

Conclusion

Capped collections provide an automatic way to limit total records by removing the oldest documents when limits are exceeded. This is useful for log collections or any scenario requiring a fixed-size data store.

Updated on: 2026-03-15T02:20:10+05:30

292 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements