In MongoDB, you can use TTL indexes to automatically delete “expired” documents at a specified time or after a specified period of time.

TTL index

TTL index is a special single-field index in MongoDB, where the field type must be ISODate type or contain an array with ISODate type.

Creating a TTL index is the same as creating a normal index, but with an additional attribute

Db.collection name. CreateIndex ({"ISODate type fields ": 1}, {expireAfterSeconds: expiration time, in seconds}, {background: true})Copy the code
  • If the index field is an array and there are multiple date values in the field, MongoDB uses the earliest date value in the array to calculate the expiration threshold.

  • If the index field in the document is not of type ISODate or contains an array of type ISODate, the document will not expire.

  • If a document does not contain an index field (the index field was incorrectly specified), the document will not expire.

In addition, if the value of expireAfterSeconds is set to 0, the expiration time is determined by the time of the index field. With this feature you can add a field of type ISODate to your collection, insert an expiration date and specify it as a TTL index field, indirectly implementing expiration at a specified time.

Like other indexes, TTL indexes support query optimization

TTL Index mechanism

After you set up the TTL index for a field in the set, a thread will be started in the background to continuously query the index value (once in 60 seconds by default) to determine whether the document is expired. If it is, the document will be deleted. However, the deletion action may not be executed immediately, depending on the load of mongo instance. There may be a slight delay in deleting.

It is also important to note that in a replica cluster, only the master node starts the TTL background thread, and if this instance becomes a replica node, the background thread is idle