c# - 嵌套文档上的 MongoDb TTL 是可能的吗?

标签 c# mongodb indexing mongodb-.net-driver ttl

我想知道是否可以在嵌套文档上使用 TTL。

场景

我有 Account,里面有 SessionsSessions 需要在 30 分钟后过期。我已经设置了所有内容,但很明显,当我在 Account.Sessions.EndDateTime 上设置 TTL 索引时,它会删除整个 Account。我可以确保它只删除 Session 吗?

这就是它在数据库中的样子。注意当 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")
        }
    ]
}

这是我创建上述索引的地方。

if (!_db.Accounts.IndexExists("Sessions.EndDateTime"))
{
    _db.Accounts.CreateIndex(IndexKeys.Ascending("Sessions.EndDateTime"),
        IndexOptions.SetTimeToLive(new TimeSpan(0)));
}

最佳答案

目前无法使用 TTL 索引。 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.

我建议您将 session 子文档存储在单独的集合中,并在该集合上添加 TTL 索引。

如果您无法更改架构,另一种方法是创建一个后台作业,该作业将每 60 秒从您的集合中删除嵌套文档。

关于c# - 嵌套文档上的 MongoDb TTL 是可能的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24470774/

相关文章:

php - MongoDB php驱动程序导致XAMPP OS X上的apache失败

安卓适配器 "java.lang.IndexOutOfBoundsException: Invalid index 4, size is 4"

r - 如何在R中根据网格索引坐标数据?

c# - WorklistQuery (C-FIND) 返回 C-Find 响应 [2] : Optional Keys Not Supported

c# - Entity Framework 核心 : How to include a null related Entity with its null column properties?

c# - 如何从控制台应用程序跟踪 MongoDB 请求

indexing - 构建 REST API 的在线文档

c# - 如何在进程停止时取消虚拟主机

c# - Xaml 绑定(bind)全景 Windows Phone 8

mongodb - 命令失败,错误 16020 (Location16020) : 'Expression $eq takes exactly 2 arguments. 1 were passed in.' on server localhost:27017