cringe
cringe

Reputation: 13970

Is it possible to expire data in MongoDB based on multiple properties?

I'm trying to clean up my MongoDB and I thought about adding a TTL index to expire documents. But I need different TTLs for my documents, based on a 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 a TTL on property timestamp, but I need a different TTL based on serviceId. Is this possible in MongoDB 2.2.x?

Upvotes: 3

Views: 3117

Answers (2)

cubbuk
cubbuk

Reputation: 7920

While @Philipp's answer is quite useful. There is another way too. You can add a new field to your collection which holds a timestamp for serviceId, and have two TTL indexes seperately one on timestamp and the other on serviceIdTimestamp.

Upvotes: 0

Philipp
Philipp

Reputation: 69663

No, a TTL index does not contain any conditional logic except if field < now - expireAfterSeconds then delete document.

However, there might be a workaround which could work in your situation: When you have a specific date in the future where you want your document to expire, you can add a field expireDate which you set to the date in the future where you want the document to expire. When you then create the index with expireAfterSeconds to 0, each document will be deleted when its expireDate has passed. This trick allows you to have documents with different TTLs in the same collection.

Upvotes: 4

Related Questions