Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different TTL for different documents that are in same collection?

I am using AdministratorSession collection for my sessions. When he clicks "Remember Me" I want session document to be deleted after 3600 minutes, otherwise 30 minutes. Is it possible? If not then what are my options?

I've tried using simple approach right here but it creates index and sets TTL value to the first document that is created. For example if one document ttl is set to 30 and next to 3600 they both will be deleted after 30 minutes.

Here is how I accomplish this currently.

public AdministratorSession Add(string ip, bool remember)
{
    var random = new Random();

    var session = new AdministratorSession
    {
        StartDateTime = DateTime.Now,
        Hash = EncryptionService.Sha256(DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture)),
        Salt = EncryptionService.Md5(ip + random.Next(0, 1000))
    };

    var db = DbContext.GetDatabase();
    var collection = db.GetCollection<AdministratorSession>("AdministratorSession");

    collection.EnsureIndex(IndexKeys.Ascending("StartDateTime"), IndexOptions.SetTimeToLive(TimeSpan.FromMinutes(remember ? 36000 : 30)));
    collection.Insert(session);

    return session;
}
like image 663
Stan Avatar asked Jan 05 '14 13:01

Stan


1 Answers

MongoDBs TTL algorithm works by comparing the indexed date-field with the current date minus the time of the TTL index and deleting the document when it's smaller (if document.date < (now() - TTLduration)) delete(document);).

Instead of setting the date-field to the current time and the TTL time to how long until deletion, you can also use the mechanism the other way around: Set the TTL time to 0 and the date-field to the date when you want the document to get deleted.

like image 143
Philipp Avatar answered Sep 20 '22 02:09

Philipp