Capped Collection
- Capped collection is fixed size collection when data is exceeded the maximum size, it deletes the old records.
- An internally capped collection will maintain insertion order.
- It uses circular buffers to clean up old data.
- In realtime, if you want to log last 10days of logs we can go for Capped collection.
Create Capped collection
db.createCollection('logs', {capped:true, size:100000, max=2000}).
- In above quary, size indicates allocation of memory, max indicates max number of documents.
Update existing normal collection to Capped collection
db.runCommand({"convertToCapped": "users", size: 200000});
- But we have a problem with the capped collection is when data memory reaches max size or max number of documents it deletes old documents, it doesn't support time base delete.
- If we want to delete mongo documents based on the time we need to use TTL index based collection.
TTL index based Collection
- TTL stands for Time To Leave.
- TTL is a single field index on MongoDB collection.
- After specific time MongoDB removes the documents from the collection.
Create TTL index
db.logs.createIndex({insertdDate:1}, { expireAfterSeconds: 100000 })
- In background expiry documents will be removed by MongoDB thread for every 60 seconds.