If you're considering the expiration age in a certain context, there are two methods to approach this.
One option is to utilize "TTL indexes" which can automatically prune specific collections based on time. For example, if you have a logs table recording application events and only want to retain logs from the past hour, adding a date field to your logs document can indicate its age. MongoDB will leverage this field to determine if a document has expired and should be deleted:
db.log_events.insert({
"name": "another log entry",
"createdAt": new Date()
})
You can then create a TTL index on this field for your collection. For instance, setting an expireAfterSeconds
value of 3600 deletes logs every hour:
db.log_events.createIndex({ "createdAt": 1 }, { expireAfterSeconds: 3600 })
To customize the expiry time in seconds, refer to MongoDB's documentation on data expiration using TTL indexes.
The alternative method involves manually removing documents using a date range query. In the previous example with the log collection, to delete records older than an hour, generate a date representing an hour ago relative to the current timestamp and apply it as the query parameter in the collection's remove method:
var now = new Date(),
hourAgo = new Date(now.getTime() - (60 * 60 * 1000));
db.log_events.remove({"createdAt": { "$lte": hourAgo }})
This snippet will eliminate log entries exceeding an hour old.