0
0
MongoDBquery~3 mins

Why Capped collections for fixed-size data in MongoDB? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your database could clean itself up and never run out of space?

The Scenario

Imagine you have a small notebook where you write down your daily expenses. When the notebook is full, you have to erase old pages manually to make space for new notes.

The Problem

Manually erasing old pages is slow and you might accidentally erase important notes. Also, keeping track of what to erase wastes time and can cause mistakes.

The Solution

Capped collections automatically keep only the newest data up to a fixed size. Old data is removed without any extra work, so your storage never overflows and you always have recent information.

Before vs After
Before
db.expenses.insert({date: '2024-06-01', amount: 20}); // Manually delete old entries when full
After
db.createCollection('expenses', {capped: true, size: 10000}); // Auto-remove old data when size limit reached
What It Enables

You can store continuous streams of data without worrying about running out of space or manual cleanup.

Real Life Example

A chat app uses capped collections to keep only the latest 1000 messages, ensuring fast access and fixed storage size.

Key Takeaways

Capped collections limit data size automatically.

They remove oldest data when full, no manual cleanup needed.

Perfect for logs, caches, or real-time data streams.