Is data expiration possible in MongoDB based on multiple properties?

I am trying to clean up my MongoDB and I thought about adding a TTL index for documents expiration . But I need different TTLs for my documents based on the second property.

Here's an example:

    "_id" : ObjectId("525bd2aee4b05e96f1ec7362"),
    "payload"       : "525bd2aee4b05e96f1ec7361",
    "serviceId"     : "525bd2ade4b05e96f1ec735f",
    "status"        : "STARTED",
    "timestamp"     : ISODate("2013-10-14T11:17:01.651Z"),
    "transaction  " : "525bd2aee4b05e96f1ec7360"


I can set the TTL on the property timestamp

, but I need a different TTL based on serviceId

. Is this possible in MongoDB 2.2.x?


source to share

2 answers

No, the TTL index contains no conditional logic except if field < now - expireAfterSeconds then delete document


However, there may be a workaround that might work for your situation: when you have a specific date in the future, when you want your document to expire, you can add the field expireDate

that you set on the date at where you want the document to expire. When you create an index from expireAfterSeconds

0 to 0, each document will be deleted when it goes through it expireDate

. This trick allows you to have documents with different TTLs in the same collection.



Although @Philipp's answer is quite helpful. There is another way. You can add a new field to your collection that stores the timestamp for the serviceId and has two TTL indices separately on timestamp

and the other on serviceIdTimestamp




All Articles