0
0
MongoDBquery~30 mins

Capped collections for fixed-size data in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Create and Use a Capped Collection in MongoDB
📖 Scenario: You are managing a logging system that stores recent log messages. To save space, you want to keep only the latest 5 log entries in your database.
🎯 Goal: Build a capped collection in MongoDB that holds exactly 5 log documents. Insert 5 logs, then add one more log to see the oldest log removed automatically.
📋 What You'll Learn
Create a capped collection named logs with a maximum of 5 documents
Insert 5 log documents with fields message and level
Insert a 6th log document to trigger automatic removal of the oldest log
Query the logs collection to confirm only 5 documents remain
💡 Why This Matters
🌍 Real World
Capped collections are useful for storing logs, sensor data, or any data where only the most recent entries matter and storage space is limited.
💼 Career
Understanding capped collections helps in roles involving database management, backend development, and system monitoring where efficient data retention is important.
Progress0 / 4 steps
1
Create a capped collection named logs
Use the db.createCollection method to create a capped collection called logs with a maximum of 5 documents and a size of 10000 bytes.
MongoDB
Need a hint?

Use db.createCollection("logs", { capped: true, size: 10000, max: 5 }) to create the capped collection.

2
Insert 5 log documents into logs
Insert 5 documents into the logs collection. Each document should have a message field with values "Log 1" to "Log 5" and a level field with value "info".
MongoDB
Need a hint?

Use db.logs.insertMany([...]) with 5 documents having message and level fields.

3
Insert a 6th log document to trigger removal of the oldest log
Insert one more document into the logs collection with message set to "Log 6" and level set to "warning". This will cause the oldest document to be removed automatically.
MongoDB
Need a hint?

Use db.logs.insertOne({ message: "Log 6", level: "warning" }) to add the 6th log.

4
Query the logs collection to confirm only 5 documents remain
Use db.logs.find() to retrieve all documents from the logs collection. Confirm that only 5 documents exist and the oldest log "Log 1" is removed.
MongoDB
Need a hint?

Use db.logs.find() to see all documents in the capped collection.