2

I can create an index with expiredAfterSecconds this way in the mongo shell:

db.x.createIndex( { "createdAt": 1 }, { expireAfterSeconds: 3600 } )

I can re-do the same command and that's ok for mongo:

> db.x.createIndex( { "createdAt": 1 }, { expireAfterSeconds: 3600 } )
{
    "createdCollectionAutomatically" : false,
    "numIndexesBefore" : 2,
    "numIndexesAfter" : 2,
    "note" : "all indexes already exist",
    "ok" : 1
}

However, if I try to change the expiredAfterSecconds value re-creating the index I get and error:

> db.x.createIndex( { "createdAt": 1 }, { expireAfterSeconds: 7200 } )
{
    "ok" : 0,
    "errmsg" : "Index with name: createdAt_1 already exists with different options",
    "code" : 85,
    "codeName" : "IndexOptionsConflict"
}

The same if I use ensureIndex() instead of createIndex().

To my knowledge the only way of modifying expireAfterSeconds value I have found is to drop the index, then create it again, but I wonder if there is another way (maybe some kind of "override" option to be passed to createIndex()?).

I'm using PyMongo, so if it can solve mongo shell limitations that would be also fine to me.

fgalan
  • 11,732
  • 9
  • 46
  • 89

1 Answers1

1

As of mongo doc:

  • If a non-TTL single-field index already exists for a field, you cannot create a TTL index on the same field since you cannot create indexes that have the same key specification and differ only by the options. To change a non-TTL single-field index to a TTL index, you must drop the index first and recreate with the expireAfterSeconds option.
  • You cannot use createIndex() to change the value of expireAfterSeconds of an existing index. Instead use the collMod database command in conjunction with the index collection flag. Otherwise, to change the value of the option of an existing index, you must drop the index first and recreate.

More about using collMod is: here

As @adam-harrison mentioned in comment, check also here

klingac
  • 463
  • 3
  • 10
  • I didn't know about `collMod`. Thanks for the reference! It seems to be exactly what I need :) – fgalan Nov 05 '19 at 21:05