Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDb TTL on nested document is possible?

I want to know if it's possible to use TTL on nested documents.

Scenario

I have Account and inside I have Sessions. Sessions need to expire in 30 minutes. I've set everything up but obviously when I set TTL index on Account.Sessions.EndDateTime it removes the whole Account. Can I make sure it removes only Session?

This is what it looks like in database. Notice how it will delete whole Account and not only Session when EndDateTime will come.

{
    "_id" : ObjectId("53af273888dba003f429540b"),
    "Email" : "[email protected]",
    "PasswordHash" : "CZaBEQRbwWNgJBjyhks7gH0Z3v5ZvDkW29pryF0DEXyE8rIw0NA4x39+uQneArKaUv97sP1e+e22YT1glbqQsw==",
    "PasswordSalt" : "100000.Qx4D8uj7oDcWHRTLGRRTDwVkw2UcaM52XkDR9k2ga073Ow==",
    "Sessions" : [ 
        {
            "Token" : "da55cf0783c4249b26283948fcae6caa15df320ca456203045aea81cad691df8",
            "IpAddress" : "::1",
            "StartDateTime" : ISODate("2014-06-28T20:36:27.000Z"),
            "EndDateTime" : ISODate("2014-06-28T21:06:27.000Z")
        }
    ]
}

This is where I create said index.

if (!_db.Accounts.IndexExists("Sessions.EndDateTime"))
{
    _db.Accounts.CreateIndex(IndexKeys.Ascending("Sessions.EndDateTime"),
        IndexOptions.SetTimeToLive(new TimeSpan(0)));
}
like image 786
Stan Avatar asked Jun 28 '14 20:06

Stan


People also ask

How does TTL work in MongoDB?

The TTL feature relies on a background thread in mongod that reads the date-typed values in the index and removes expired documents from the collection.

Does MongoDB have TTL?

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

Does MongoDB support nested objects?

MongoDB delivers an upstanding feature named Embedded or Nested Document. An Embedded or Nested Document is a type of document that contains one document within another.

How do I query a nested document in MongoDB?

Accessing embedded/nested documents – In MongoDB, you can access the fields of nested/embedded documents of the collection using dot notation and when you are using dot notation, then the field and the nested field must be inside the quotation marks.


1 Answers

That is currently not possible with TTL index. Mongod will remove the whole document after a specified number of seconds or at a specific clock time.

TTL relies on a background thread in mongod that reads the date-typed values in the index and removes expired documents from the collection.

I would recommend that you store the session sub-document in a separate collection and add a TTL index on that collection.

If you can't change your schema, the alternative is to create a background job that will delete nested documents from your collection every 60 seconds.

like image 151
Christian P Avatar answered Oct 23 '22 10:10

Christian P