In this recipe, we will explore the expireAfterSeconds property of MongoDB indexes to allow automatic deletion of documents from a collection.
Creating TTL-based indexes
Getting ready
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.
How to do it...
- 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...