Beginner LevelMongoDB & Mongoose
What are Capped Collections and Tailable Cursors in MongoDB?
❓ Interview Prompt: Explain fixed-size Capped Collections, FIFO circular overwriting, insertion order preservation, and streaming Tailable Cursors.
Capped Collections are fixed-size circular collections that maintain insertion order:
Key Mechanics:
•
Allocated fixed disk size (e.g. 100MB).
•
When allocated space fills up, new document insertions automatically overwrite the oldest documents (FIFO - First In First Out).
•
Tailable Cursors: Cursors that remain open after reaching the end of data, streaming new incoming documents in real time (ideal for high-throughput logging!).
Code Implementation Example
typescript
import mongoose from 'mongoose';
// Create a 50MB capped collection for live log streaming
const logSchema = new mongoose.Schema({ message: String, timestamp: Date });
const LogModel = mongoose.model('SystemLog', logSchema, 'system_logs');
async function createCappedCollection() {
await mongoose.connection.createCollection('system_logs', {
capped: true,
size: 52428800 // 50MB
});
}💡Creating a fixed-size capped collection for high-speed logging.
🎯 Interview Key Takeaway
Use Capped Collections for high-throughput logging and event streaming where fixed storage caps and FIFO eviction are required.
#Capped Collections#Tailable Cursors#Streaming#Beginner
Back to all MongoDB & Mongoose Questions→