azure-cosmosdbazure-cosmosdb-mongoapi

Does CosmosDB MongoDB API support expireAfterSeconds of -1 for "Infinity" TTL?


I have a collection where different types of documents have different useful life spans. The main document for an entity should never be automatically deleted but it can have ancillary associated documents which are viable to age out by policy after a fixed period.

To that end I am looking at per document TTL.

The "Set time to live value for a document" section of the documentation states

Per-document TTL values are also supported. The document(s) must contain a root-level property "ttl" (lower-case), and a TTL index as described above must have been created for that collection. TTL values set on a document will override the collection's TTL value.

As it is mandatory for me to create a collection level ttl index do I have to set expireAfterSeconds to some high number (such as 2147483647 seconds) or will setting this value to -1 work the same way as setting the container level ttl with the NoSQL API to act as "infinite"?

The remainder of the documentation on the "Expire data with Azure Cosmos DB's API for MongoDB" page does not mention -1 as a potential value.


Solution

  • Time-to-live (ttl) with MongoDB API follows the same rules as the core SQL API (it even utilizes the _ts property in the background, for its operation).

    You can indeed set ttl to -1 as the collection-level default (meaning... don't expire), and then override with ttl on specific documents. Something like this should work, to enable ttl on a collection with no deletion, by default:

    db.coll.createIndex( {"_ts":1}, {expireAfterSeconds: -1} )
    

    Then you can override, on a per-document basis:

    db.mycollection.insert( {someProperty: "some value", ttl: 3600 })
    

    For reference: this doc describes the MongoDB API rules for ttl, including this explicit mention of behavior being the same as with the SQL API:

    The logic governing TTL indexes and per-document TTL values in Azure Cosmos DB's API for MongoDB is the same as in Azure Cosmos DB.