4

I'm trying to create a collection named ttl, and using a TTL index, make the documents in that collection expire after 30 seconds.

I've created the collection using mongoengine, like so:

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

    expire_at = DateTimeField()

The index has been created and Robo3T shows it's as expected.

The actual documents are inserted to the collection using mongoengine as well:

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

The save is successful (the document is inserted into the DB), but it never expires!

How can I make the documents expire?

I'm adding the collection's contents here as well in case I'm saving them wrong. These are the results of running 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")
}

The indexes themselves, as per the results of db.getCollection('ttl').getIndexes(), are:

/* 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
    }
]

My db.version() is 4.0.8 and it's running on Ubuntu 18.04.

3
  • Please post the output of db.ttl.getIndexes() from the mongo shell (not from Robo3T). I have a hunch that the TTL index was not setup like you expected.
    – kevinadi
    May 6, 2019 at 5:16
  • Hi @KevinAdistambha I added the indexes of the collection to the question's body, any ideas? May 6, 2019 at 14:48
  • Also added the DB version ¯_(ツ)_/¯ May 6, 2019 at 14:53

1 Answer 1

2

The issue is with:

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

that should be

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.