简体   繁体   English

嵌套文档上的MongoDb TTL是否可以?

[英]MongoDb TTL on nested document is possible?

I want to know if it's possible to use TTL on nested documents. 我想知道是否可以在嵌套文档上使用TTL。

Scenario 情境

I have Account and inside I have Sessions . 我有Account ,内部有Sessions Sessions need to expire in 30 minutes. Sessions需要在30分钟后过期。 I've set everything up but obviously when I set TTL index on Account.Sessions.EndDateTime it removes the whole Account . 我已经进行了所有设置,但是很显然,当我在Account.Sessions.EndDateTime上设置TTL索引时,它将删除整个Account Can I make sure it removes only Session ? 我可以确保它仅删除Session吗?

This is what it looks like in database. 这就是数据库中的样子。 Notice how it will delete whole Account and not only Session when EndDateTime will come. 请注意,当EndDateTime到来时,它将如何删除整个Account ,而不只是Session

{
    "_id" : ObjectId("53af273888dba003f429540b"),
    "Email" : "steve@s3te5ve.com",
    "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)));
}

That is currently not possible with TTL index. 目前无法使用TTL索引。 Mongod will remove the whole document after a specified number of seconds or at a specific clock time. Mongod将在指定的秒数或特定的时钟时间后删除整个文档。

TTL relies on a background thread in mongod that reads the date-typed values in the index and removes expired documents from the collection. TTL依赖于mongod中的一个后台线程,该线程读取索引中日期类型的值,并从集合中删除过期的文档

I would recommend that you store the session sub-document in a separate collection and add a TTL index on that collection. 我建议您将会话子文档存储在单独的集合中,并在该集合上添加TTL索引。

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. 如果您无法更改架构,则替代方法是创建一个后台作业,该作业每60秒从您的集合中删除嵌套的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM