Home > Net >  MongoDB does not remove documents from a collection with a configured TTL Index
MongoDB does not remove documents from a collection with a configured TTL Index

Time:01-27

I try to get started with TTL indices in mongo, and wanted to get a simple demo setup running, but I just cannot get it to work and I am not sure what I do wrong.

Mongod version:

$ mongod --version
db version v4.4.5
Build Info: {
    "version": "4.4.5",
    "gitVersion": "ff5cb77101b052fa02da43b8538093486cf9b3f7",
    "openSSLVersion": "OpenSSL 1.1.1m  14 Dec 2021",
    "modules": [],
    "allocator": "tcmalloc",
    "environment": {
        "distmod": "debian10",
        "distarch": "x86_64",
        "target_arch": "x86_64"
    }
}

I start with a completely fresh, default configured mongod instance:

$ mkdir /tmp/db && mongod --dbpath /tmp/db

Then I run the following commands

use test

db.ttldemo.insertOne({
    created_at: Date(Date.now()   60_000)
})


db.ttldemo.createIndex({created_at: 1}, {expireAfterSeconds: 1})

db.ttldemo.find()

I would expect the document to vanish after some time, but even after running find() after waiting for a few minutes, the document is still present.

Is there anything I am missing here?

db.adminCommand({getParameter:1, ttlMonitorSleepSecs: 1}) yields 60 to me

CodePudding user response:

I tried in mongo 4.2.17, your insertion of documents yields a document like:

{
    "_id" : ObjectId("61f17ea34844b5f0505d80ea"),
    "created_at" : "Wed Jan 26 2022 19:02:27 GMT 0200 (GTB Standard Time)"
}

when the

db.getCollection('ttldemo').insertOne({created_at: new Date()})

yields a document like:

{
    "_id" : ObjectId("61f17f404844b5f0505d80ec"),
    "created_at" : ISODate("2022-01-26T17:05:04.023Z")
}

Emphasis here on the created_at field, where this on the first case is a string, in the second case is an ISODate. as from the documentation , this index works on dates only:

To create a TTL index, use the createIndex() method on a field whose value is either a date or an array that contains date values, and specify the expireAfterSeconds option with the desired TTL value in seconds.

The solution here is to construct the date as follows:

db.getCollection('ttldemo').insertOne({created_at: new Date(new Date().getTime() 60000)})

this will create a new ISODate based on the current date 60 seconds.

  •  Tags:  
  • Related