适用对象:
MongoDB
生存时间 (TTL) 功能允许数据库将数据自动过期。 Azure Cosmos DB for MongoDB 利用 Azure Cosmos DB 的核心 TTL 功能。 支持两种模式:一是在整个集合上设置默认的 TTL 值,二是为每个文档设置单独的 TTL 值。 管理 Azure Cosmos DB for MongoDB 中 TTL 索引和每文档 TTL 值的逻辑 与 Azure Cosmos DB 中的逻辑相同。
若要在集合上普遍启用 TTL,需创建“TTL 索引”(生存时间索引)。 TTL 索引是 _ts
字段上的索引,其值为“expireAfterSeconds”。
MongoShell 示例:
globaldb:PRIMARY> db.coll.createIndex({"_ts":1}, {expireAfterSeconds: 10})
上一示例中的命令创建具有 TTL 功能的索引。
命令的输出包括各种元数据:
{
"_t" : "CreateIndexesResponse",
"ok" : 1,
"createdCollectionAutomatically" : true,
"numIndexesBefore" : 1,
"numIndexesAfter" : 4
}
创建索引以后,数据库会自动删除集合中未在过去 10 秒内修改的任何文档。
备注
_ts
是特定于 Azure Cosmos DB 的字段,无法从 MongoDB 客户端访问。 它是包含文档上次修改时间戳的保留(系统)属性。
Java 示例:
MongoCollection collection = mongoDB.getCollection("collectionName");
String index = collection.createIndex(Indexes.ascending("_ts"),
new IndexOptions().expireAfter(10L, TimeUnit.SECONDS));
C# 示例:
var options = new CreateIndexOptions {ExpireAfter = TimeSpan.FromSeconds(10)};
var field = new StringFieldDefinition<BsonDocument>("_ts");
var indexDefinition = new IndexKeysDefinitionBuilder<BsonDocument>().Ascending(field);
await collection.Indexes.CreateOneAsync(indexDefinition, options);
按文档 TTL 值也受支持。 一个或多个文档必须包含根级属性“ttl”(小写),并且之前必须为该集合创建 TTL 索引。 文档上设置的 TTL 值将替代集合的 TTL 值。
TTL 值必须是 int32。 也可以是属于 int32 的 int64,或者是没有任何小数部分属于 int32 的 double。 不符合这些规范的 TTL 属性值是允许的,但不会被系统视为有意义的文档 TTL 值。
文档的 TTL 值为可选;没有 TTL 值的文档可以插入集合中。 在这种情况下,将使用集合的 TTL 值。
以下文档具有有效的 TTL 值。 插入文档以后,文档 TTL 值会替代集合的 TTL 值。 因此,会在 20 秒后删除文档。
globaldb:PRIMARY> db.coll.insert({id:1, location: "Paris", ttl: 20.0})
globaldb:PRIMARY> db.coll.insert({id:1, location: "Paris", ttl: NumberInt(20)})
globaldb:PRIMARY> db.coll.insert({id:1, location: "Paris", ttl: NumberLong(20)})
以下文档的 TTL 值无效。 文档已插入,但文档 TTL 值不会被接受。 因此,文档会在 10 秒后被删除,因为使用的是集合的 TTL 值。
globaldb:PRIMARY> db.coll.insert({id:1, location: "Paris", ttl: 20.5}) //TTL value contains non-zero decimal part.
globaldb:PRIMARY> db.coll.insert({id:1, location: "Paris", ttl: NumberLong(2147483649)}) //TTL value is greater than Int32.MaxValue (2,147,483,648).