0

I'm using mongojs to interact with mongodb in my app.

I need to add TTL support for the collection making the documents delete themselves every hour. Here's how I'm creating index on app start:

db.collection.ensureIndex({'createdAt': 1, expireAfterSeconds: 3600})

The createdAt field is inited as new Date() when saving document.

Here's how the documents' structure looks in the database:

{
"_id" : ObjectId("5425759f73070ab82f6097ca"),
"user" : "bde8349VIO2RpmhE9Rkn3qvQJDYkr589MeWdsopEteQ3OfxQVPxUhLWH0AMiwnypKhquNEG4eA==",
"tags" : [],
"createdAt" : ISODate("2014-09-26T14:18:07.041Z")
}

I checked indexes inside database and they look fine:

> db.collection.getIndexes()
[
{
    "v" : 1,
    "key" : {
        "_id" : 1
    },
    "name" : "_id_",
    "ns" : "dbname.collection"
},
{
    "v" : 1,
    "key" : {
        "createdAt" : 1,
        "expireAfterSeconds" : 3600
    },
    "name" : "createdAt_1_expireAfterSeconds_3600",
    "ns" : "dbname.collection"
}
]

But all documents stay inside db and are not deleted.. Any ideas?

Thanks!

Kosmetika
  • 20,774
  • 37
  • 108
  • 172

1 Answers1

2

It should be db.collection.ensureIndex({'createdAt': 1}, {expireAfterSeconds: 3600}) but not db.collection.ensureIndex({'createdAt': 1, expireAfterSeconds: 3600}).

Wizard
  • 4,341
  • 1
  • 15
  • 13
  • For those who halted for a few seconds trying to spot the difference between both statements, the difference is the first is correctly constructed by specifying `expireAfterSeconds` as a second Index creation option. – Muhammad Gelbana Sep 29 '17 at 23:47