Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can individual fields be set to expire in MongoDB?

Tags:

mongodb

ttl

I would like to know if it is possible to expire individual fields in a document rather than the entire document.

Having read the documentation on TTL Indexes and Expiring Data, it would appear that it is only possible to expire documents based on a field however I would like to confirm.

The background for this question is that I have a Statistics collection with fields for monthly, weekly, daily and hourly statistics in each document. I could break this up into 4 separate collections such that the documents in each collection could use a different TTL, however I believe this would also mean that I would need to correspondingly break my bulk updates into one bulk update per collection. I would like to keep the efficiency benefit of one single bulk operation if possible.

like image 271
aerospatiale Avatar asked Sep 15 '14 01:09

aerospatiale


People also ask

How does MongoDB expire data?

To expire documents at a specific clock time, begin by creating a TTL index on a field that holds values of BSON date type or an array of BSON date-typed objects and specify an expireAfterSeconds value of 0 .

How does TTL work in MongoDB?

TTL (Time-To-Live) indexes are special single-field indexes that MongoDB can use to automatically remove documents from a collection after a certain amount of time. A background thread in MongoDB reads the values in the index and removes expired documents from the collection (usually every minute).

What is TTL index in MongoDB?

TTL Indexes indexes are single-field indexes that MongoDB can use to remove documents from a collection after a certain amount of time or at a specific clock time.

Which field in MongoDB is automatically?

Architecturally, by default the _id field is an ObjectID, one of MongoDB's BSON types. The ObjectID is the primary key for the stored document and is automatically generated when creating a new document in a collection.


1 Answers

It is impossible so far.

Your solution is ok if it is not a write heavy db. While if you want to reduce the writing frequency, there is another solution: Running a timer on certain server, which is used to query expired documents every 1 minute from slave mongo instance (or several minutes, depends on the accuracy you need). Then manually update these documents.

like image 198
Mark_H Avatar answered Oct 19 '22 04:10

Mark_H