【问题标题】:MongoDB TTL index doesn't delete expired documentsMongoDB TTL 索引不会删除过期文档
【发布时间】:2019-09-23 10:49:01
【问题描述】:

我正在尝试创建一个名为 ttl 的集合,并使用 TTL 索引使该集合中的文档在 30 秒后过期。

我使用mongoengine 创建了集合,如下所示:

class Ttl(Document):
    meta = {
        'indexes': [
            {
                'name': 'TTL_index',
                'fields': ['expire_at'],
                'expireAfterSeconds': 0
            }
        ]
    }

    expire_at = DateTimeField()

索引已创建,Robo3T 显示它符合预期。

实际文档也使用mongoengine 插入到集合中:

current_ttl = models.monkey.Ttl(expire_at=datetime.now() + timedelta(seconds=30))
current_ttl.save()

保存成功(文档插入DB),但永不过期!

如何使文件过期?

我也在此处添加集合的内容,以防我保存错误。这些是运行db.getCollection('ttl').find({})的结果:

/* 1 */
{
    "_id" : ObjectId("5ccf0f5a4bdc6edcd3773cd6"),
    "created_at" : ISODate("2019-05-05T19:31:10.715Z")
}

/* 2 */
{
    "_id" : ObjectId("5ccf121c0b792dae8f55cc80"),
    "expire_at" : ISODate("2019-05-05T19:41:08.220Z")
}

/* 3 */
{
    "_id" : ObjectId("5ccf127d6729084a24772fad"),
    "expire_at" : ISODate("2019-05-05T19:42:47.522Z")
}

/* 4 */
{
    "_id" : ObjectId("5ccf15bab124a97322da28de"),
    "expire_at" : ISODate("2019-05-05T19:56:56.359Z")
}

根据db.getCollection('ttl').getIndexes() 的结果,索引本身是:

/* 1 */
[
    {
        "v" : 2,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "monkeyisland.ttl"
    },
    {
        "v" : 2,
        "key" : {
            "expire_at" : 1
        },
        "name" : "TTL_index",
        "ns" : "monkeyisland.ttl",
        "background" : false,
        "expireAfterSeconds" : 0
    }
]

我的db.version() 是 4.0.8,它在 Ubuntu 18.04 上运行。

【问题讨论】:

  • 请从mongo shell(不是来自Robo3T)发布db.ttl.getIndexes() 的输出。我有预感 TTL 索引没有像你预期的那样设置。
  • 嗨@KevinAdistambha 我将集合的索引添加到问题的正文中,有什么想法吗?
  • 还添加了DB版本¯_(ツ)_/¯

标签: python mongodb mongoengine robo3t


【解决方案1】:

问题在于:

current_ttl = models.monkey.Ttl(expire_at=datetime.now() + timedelta(seconds=30))

应该是这样的

current_ttl = models.monkey.Ttl(expire_at=datetime.utcnow() + timedelta(seconds=30))

【讨论】:

    猜你喜欢
    • 2016-08-03
    • 2016-03-22
    • 2014-05-05
    • 2013-09-14
    • 2016-04-20
    • 1970-01-01
    • 2017-10-13
    • 1970-01-01
    相关资源
    最近更新 更多