TTL Indexes索引

On this page本页内容

Note注意

If you are removing documents to save on storage costs, consider Online Archive in MongoDB Atlas. 如果要删除文档以节省存储成本,请考虑MongoDB Atlas中的在线存档Online Archive automatically archives infrequently accessed data to fully-managed S3 buckets for cost-effective data tiering.在线存档自动将不经常访问的数据存档到完全管理的S3存储桶中,以实现经济高效的数据分层。

TTL indexes are special single-field indexes that MongoDB can use to automatically remove documents from a collection after a certain amount of time or at a specific clock time. TTL索引是特殊的单字段索引,MongoDB可以使用它在一定时间后或特定时钟时间自动从集合中删除文档。Data expiration is useful for certain types of information like machine generated event data, logs, and session information that only need to persist in a database for a finite amount of time.数据过期对于某些类型的信息非常有用,如机器生成的事件数据、日志和会话信息,这些信息只需要在数据库中保留有限的时间。

Create a TTL Index创建TTL索引

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.要创建TTL索引,请对值为日期或包含日期值的数组的字段使用createIndex()方法,并使用所需的TTL值(以秒为单位)指定expireAfterSeconds选项。

For example, to create a TTL index on the lastModifiedDate field of the eventlog collection, with a TTL value of 3600 seconds, use the following operation in mongosh:例如,要在eventlog集合的lastModifiedDate字段上创建TTL索引(TTL值为3600秒),请在mongosh中使用以下操作:

db.eventlog.createIndex( { "lastModifiedDate": 1 }, { expireAfterSeconds: 3600 } )

Convert a non-TTL single-field Index into a TTL Index将非TTL单字段索引转换为TTL索引

Starting in MongoDB 5.1, you can add the expireAfterSeconds option to an existing single-field index. 从MongoDB 5.1开始,您可以将expireAfterSeconds选项添加到现有的单字段索引中。To change a non-TTL single-field index to a TTL index, use the collMod database command:要将非TTL单字段索引更改为TTL索引,请使用collMod数据库命令:

db.runCommand({
  "collMod": <collName>,
  "index": {
    "keyPattern": <keyPattern>,
    "expireAfterSeconds": <number>
  }
})

The following example converts a non-TTL single-field index with the pattern { "lastModifiedDate": 1 } into a TTL index:以下示例将模式为{ "lastModifiedDate": 1 }的非TTL单字段索引转换为TTL索引:

db.runCommand({
  "collMod": "tickets",
  "index": {
    "keyPattern": { "lastModifiedDate": 1 },
    "expireAfterSeconds": 100
  }
})

Change the expireAfterSeconds value for a TTL Index更改TTL索引的expireAfterSeconds

To change the expireAfterSeconds value for a TTL Index, use the collMod database command:要更改TTL索引的expireAfterSeconds值,请使用collMod数据库命令:

db.runCommand({
  "collMod": <collName>,
  "index": {
    "keyPattern": <keyPattern>,
    "expireAfterSeconds": <number>
  }
})

The following example changes the expireAfterSeconds value for an index with the pattern { "lastModifiedDate": 1 } on the tickets collection:以下示例更改了tickets集合上具有模式{ "lastModifiedDate": 1 }的索引的expireAfterSeconds值:

db.runCommand({
  "collMod": "tickets",
  "index": {
    "keyPattern": { "lastModifiedDate": 1 },
    "expireAfterSeconds": 100
  }
})

Behavior行为

Expiration of Data数据过期

TTL indexes expire documents after the specified number of seconds has passed since the indexed field value; i.e. the expiration threshold is the indexed field value plus the specified number of seconds.TTL索引在自索引字段值起经过指定秒数后使文档过期;即,过期阈值是索引字段值加上指定的秒数。

If the field is an array, and there are multiple date values in the index, MongoDB uses lowest (i.e. earliest) date value in the array to calculate the expiration threshold.如果字段是数组,并且索引中有多个日期值,MongoDB将使用数组中的最低(即最早)日期值来计算过期阈值。

If the indexed field in a document is not a date or an array that holds one or more date values, the document will not expire.如果文档中的索引字段不是日期或包含一个或多个日期值的数组,则文档不会过期。

If a document does not contain the indexed field, the document will not expire.如果文档不包含索引字段,则该文档不会过期。

Delete Operations删除操作

A background thread in mongod reads the values in the index and removes expired documents from the collection.mongod中的后台线程读取索引中的值,并从集合中删除过期文档

When the TTL thread is active, you will see delete operations in the output of db.currentOp() or in the data collected by the database profiler.当TTL线程处于活动状态时,您将在db.currentOp()的输出或数据库探查器集合的数据中看到删除操作。

Timing of the Delete Operation删除操作的定时

MongoDB begins removing expired documents as soon as the index finishes building on the primary. 一旦索引在primary上构建完成,MongoDB就开始删除过期文档。For more information on the index build process, see Index Builds on Populated Collections.有关索引生成过程的更多信息,请参阅在已填充集合上生成索引

The TTL index does not guarantee that expired data will be deleted immediately upon expiration. TTL索引不能保证过期数据在过期后立即删除。There may be a delay between the time a document expires and the time that MongoDB removes the document from the database.文档过期与MongoDB从数据库中删除文档之间可能存在延迟。

The background task that removes expired documents runs every 60 seconds. 删除过期文档的后台任务每60秒运行一次。As a result, documents may remain in a collection during the period between the expiration of the document and the running of the background task.因此,在文档过期和后台任务运行之间的时间段内,文档可能会保留在集合中。

Because the duration of the removal operation depends on the workload of your mongod instance, expired data may exist for some time beyond the 60 second period between runs of the background task.由于删除操作的持续时间取决于mongod实例的工作负载,因此过期数据可能会存在一段时间,超过后台任务运行间隔的60秒。

Replica Sets复制集

On replica set members, the TTL background thread onlydeletes documents when a member is in state primary. 副本集成员上,TTL后台线程在成员处于primary状态时删除文档。The TTL background thread is idle when a member is in state secondary. 当成员处于secondary状态时,TTL后台线程处于空闲状态。Secondary members replicate deletion operations from the primary.secondary成员从主要成员复制删除操作。

Support for Queries支持查询

A TTL index supports queries in the same way non-TTL indexes do.TTL索引支持查询的方式与非TTL索引相同。

Restrictions限制

←  Index PropertiesExpire Data from Collections by Setting TTL →