Expire Data from Collections by Setting TTL通过设置TTL使集合中的数据过期
On this page本页内容
This document provides an introduction to MongoDB's "time to live" or TTL collection feature. 本文档介绍了MongoDB的“生存时间”或TTL集合功能。TTL collections make it possible to store data in MongoDB and have the TTL集合可以将数据存储在MongoDB中,并使mongod
automatically remove data after a specified number of seconds or at a specific clock time.mongod
在指定的秒数或特定的时钟时间自动删除数据。
Data expiration is useful for some classes of information, including machine generated event data, logs, and session information that only need to persist for a limited period of time.数据过期对于某些类别的信息很有用,包括机器生成的事件数据、日志和会话信息,这些信息只需要持续一段有限的时间。
A special TTL index property supports the implementation of TTL collections. 一个特殊的TTL索引属性支持TTL集合的实现。The TTL feature relies on a background thread in TTL功能依赖于mongod
that reads the date-typed values in the index and removes expired documents from the collection.mongod
中的后台线程,该线程读取索引中的日期类型值并从集合中删除过期文档。
To create a TTL index, use 要创建TTL索引,请使用createIndex()
. createIndex()
。Specify an index field that is either a date type or an array that contains date type values. 指定一个索引字段,该字段可以是日期类型,也可以是包含日期类型值的数组。Use the 使用expireAfterSeconds
option to specify a TTL value in seconds.expireAfterSeconds
选项可以指定以秒为单位的TTL值。
The TTL index is a single field index. Compound indexes do not support the TTL property. TTL索引是一个单字段索引。复合索引不支持TTL属性。For more information on TTL indexes, see TTL Indexes.有关TTL索引的更多信息,请参阅TTL索引。
You can modify the 您可以使用expireAfterSeconds
of an existing TTL index using the collMod
command.collMod
命令修改现有TTL索引的expireAfterSeconds
。
Expire Documents after a Specified Number of Seconds在指定的秒数后使文档过期
To expire data after a specified number of seconds has passed since the indexed field, create a TTL index on a field that holds values of BSON date type or an array of BSON date-typed objects and specify a positive non-zero value in the 若要在索引字段后经过指定秒数后使数据过期,请在包含BSON日期类型值或BSON日期型对象数组的字段上创建TTL索引,并在expireAfterSeconds
field. expireAfterSeconds
字段中指定一个非零值。A document will expire when the number of seconds in the 当expireAfterSeconds
field has passed since the time specified in its indexed field. expireAfterSeconds
字段中的秒数超过其索引字段中指定的时间后,文档将过期。[1]
The TTL index TTL索引expireAfterSeconds
value must be within 0
and 2147483647
inclusive.expireAfterSeconds
值必须介于0
和2147483647
之间(包括0
和2147463647
)。
For example, the following operation creates an index on the 例如,以下操作在log_events
collection's createdAt
field and specifies the expireAfterSeconds
value of 10
to set the expiration time to be ten seconds after the time specified by createdAt
.log_events
集合的createdAt
字段上创建一个索引,并指定expireAfterSeconds
值10
,以将过期时间设置为createdAt
指定时间后的10秒。
db.log_events.createIndex( { "createdAt": 1 }, { expireAfterSeconds: 10 } )
When adding documents to the 将文档添加到log_events
collection, set the createdAt
field to the current time:log_events
集合时,将createdAt
字段设置为当前时间:
db.log_events.insertOne( {
"createdAt": new Date(),
"logEvent": 2,
"logMessage": "Success!"
} )
MongoDB will automatically delete documents from the 当文档的log_events
collection when the document's createdAt
value [1] is older than the number of seconds specified in expireAfterSeconds
.createdAt
值[1]超过expireAfterSeconds
中指定的秒数时,MongoDB将自动从log_events
集合中删除文档。
[1] | (1, 2) expireAfterSeconds .expireAfterSeconds 中指定的秒数,则数据将过期。 |
Expire Documents at a Specific Clock Time在特定的时钟时间使文档过期
To expire documents at a specific clock time, begin by creating a TTL index on a field that holds values of BSON date type or an array of BSON date-typed objects and specify an 要在特定的时钟时间使文档过期,请首先在包含BSON日期类型值或BSON日期型对象数组的字段上创建TTL索引,然后指定expireAfterSeconds
value of 0
. expireAfterSeconds
值0
。For each document in the collection, set the indexed date field to a value corresponding to the time the document should expire. 对于集合中的每个文档,将索引日期字段设置为与文档到期时间相对应的值。If the indexed date field contains a date in the past, MongoDB considers the document expired.如果索引日期字段包含过去的日期,MongoDB会认为该文档已过期。
For example, the following operation creates an index on the 例如,以下操作在log_events
collection's expireAt
field and specifies the expireAfterSeconds
value of 0
:log_events
集合的expireAt
字段上创建索引,并指定expireAfterSeconds
值0
:
db.log_events.createIndex( { "expireAt": 1 }, { expireAfterSeconds: 0 } )
For each document, set the value of 对于每个文档,将expireAt
to correspond to the time the document should expire. expireAt
的值设置为与文档到期的时间相对应。For example, the following 例如,以下insertOne()
operation adds a document that expires at July 22, 2013 14:00:00
.insertOne()
操作将添加一个在July 22, 2013 14:00:00
到期的文档。
db.log_events.insertOne( {
"expireAt": new Date('July 22, 2013 14:00:00'),
"logEvent": 2,
"logMessage": "Success!"
} )
MongoDB will automatically delete documents from the 当文档的log_events
collection when the documents' expireAt
value is older than the number of seconds specified in expireAfterSeconds
, i.e. 0
seconds older in this case. expireAt
值早于expireAfterSeconds
中指定的秒数时,MongoDB将自动从log_events
集合中删除文档,即在这种情况下早0秒。As such, the data expires at the specified 因此,数据将在指定的expireAt
value.expireAt
值处过期。
Indexes Configured Using NaN使用NaN配置的索引
Possible Data Loss可能的数据丢失
When a TTL index has 当TTL索引expireAfterSeconds
set to NaN
, upgrade, downgrade, and certain syncing operations can lead to unexpected behavior and possible data loss.expireAfterSeconds
设置为NaN
时,升级、降级和某些同步操作可能会导致意外行为和可能的数据丢失。
Do not set 请勿在TTL索引配置中将expireAfterSeconds
to NaN
in your TTL index configuration.expireAfterSeconds
设置为NaN
。
Prior to MongoDB 5.0, when a TTL index has 在MongoDB 5.0之前,当TTL索引expireAfterSeconds
set to NaN
, MongoDB logs an error and does not remove any records.expireAfterSeconds
设置为NaN
时,MongoDB会记录一个错误,并且不会删除任何记录。
From MongoDB 5.0.0 - 5.0.13 (and 6.0.0 - 6.0.1), 在MongoDB 5.0.0-5.0.13(和6.0.0-6.0.1)中,NaN
is treated as 0
. NaN
被视为0
。If a TTL index is configured with 如果TTL索引配置为expireAfterSeconds
set to NaN
, all TTL-indexed documents expire immediately.expireAfterSeconds
设置为NaN
,则所有TTL索引文档将立即过期。
Starting in MongoDB 5.0.14 (and 6.0.2), the server will not use TTL indexes that have 从MongoDB 5.0.14(和6.0.2)开始,服务器将不会使用expireAfterSeconds
set to NaN
.expireAfterSeconds
设置为NaN
的TTL索引。
However, there are still some situations which may result in unexpected behavior. Documents may expire:然而,仍有一些情况可能会导致意外行为。文件可能会过期:
During an initial sync to an earlier version from MongoDB 5.0.0 - 5.0.13 (or 6.0.0 - 6.0.1).在初始同步到MongoDB 5.0.0-5.0.13(或6.0.0-6.0.1)的早期版本期间。When upgrading from an earlier version to MongoDB 5.0.0 - 5.0.13.从早期版本升级到MongoDB 5.0.0-5.0.13时。When restoring a collection from a pre-5.0将集合从5.0之前的mongodump
into a MongoDB 5.0.0 - 5.0.13 (or 6.0.0 - 6.0.1) instance.mongodump
恢复到MongoDB 5.0.0-5.0.13(或6.0.0-6.0.1)实例时。
To avoid problems, either drop or correct any misconfigured TTL indexes.为避免出现问题,请删除或更正任何配置错误的TTL索引。
Identify misconfigured indexes.识别配置错误的索引。
Run the following script in the 在mongosh
shell. The script does not work in the legacy mongo
shell.mongosh
shell中运行以下脚本。该脚本在遗留的mongo
shell中不起作用。
function getNaNIndexes() {
const nan_index = [];
const dbs = db.adminCommand({ listDatabases: 1 }).databases;
dbs.forEach((d) => {
const listCollCursor = db
.getSiblingDB(d.name)
.runCommand({ listCollections: 1 }).cursor;
const collDetails = {
db: listCollCursor.ns.split(".$cmd")[0],
colls: listCollCursor.firstBatch.map((c) => c.name),
};
collDetails.colls.forEach((c) =>
db
.getSiblingDB(collDetails.db)
.getCollection(c)
.getIndexes()
.forEach((entry) => {
if (Object.is(entry.expireAfterSeconds, NaN)) {
nan_index.push({ ns: `${collDetails.db}.${c}`, index: entry });
}
})
);
});
return nan_index;
};
getNaNIndexes();
Correct misconfigured indexes.更正错误配置的索引。
Use the 使用collMod
command to update any misconfigured expireAfterSeconds
values that the script found.collMod
命令更新脚本找到的任何配置错误的expireAfterSeconds
值。
As an alternative, you can 或者,您可以drop
any misconfigured TTL indexes and recreate them later using the createIndexes
command.drop
任何配置错误的TTL索引,然后使用createIndexes
命令重新创建它们。