In this recipe, we will explore the expireAfterSeconds
property of MongoDB indexes to allow automatic deletion of documents from a collection.
For this recipe, all you need is a mongod instance running. We will be creating and working on a new collection called ttlcol
in the database mydb
.
- Ensure that our collection is empty:
db.ttlcol.drop()
- Add 200 random documents:
for(var x=1; x<=100; x++){ var past = new Date() past.setSeconds(past.getSeconds() - (x * 60)) // Insert a document with timestamp in the past var doc = { foo: 'bar', timestamp: past } db.ttlcol.insert(doc) // Insert a document with timestamp in the future var future = new Date() future.setSeconds(future.getSeconds() + (x * 60)) var doc = { foo: 'bar', timestamp: future } db.ttlcol.insert(doc) }
- Check that the documents were added:
db.ttlcol.count()
- Create an index with TTL:
db.ttlcol.createIndex({timestamp:1}, {expireAfterSeconds: 10}...