

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 索引属性：过期 AfterSeconds
<a name="index-property-expireafterseconds"></a>

## 支持的索引类型
<a name="index-property-expireafterseconds-supported"></a>


| 索引类型 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
| 单字段 | 支持 | 是 | 是 | 是 | 是 | 
| 多键 | 支持 | 是 | 是 | 是 | 是 | 

使用过期AfterSeconds 选项创建存活时间 (TTL) 索引。使用 TTL 索引，您可以根据每个文档的超时条件根据文档的使用期限删除文档。当文档达到指定的 TTL 期限时，它会从收藏中删除。

有关 TTL 删除的最佳实践，请参阅[TTL 和时间序列工作负载](best_practices.md#best_practices-ttl_timeseries)。

## 示例
<a name="index-property-expireafterseconds-examples"></a>

以下示例说明如何在以下示例文档中创建 TTL 索引：

```
{
  "productId": "PROD133726",
  "sku": "SKU24224",
  "name": "Basic Printer",
  "manufacturer": "The Manufacturer",
  "tags": [ "printer", "basic", "electronics", "business" ],
  "barcodes": [ "542364671", "886330670", "437445606" ],
  "reviews": [
    {
      "review_date": ISODate('2024-01-19T21:37:10.585Z'),
      "rating": 4,
      "comment": "Good product"
    },
    {
      "review_date": ISODate('2024-03-15T14:22:33.120Z'),
      "rating": 5,
      "comment": "Excellent printer"
    },
    {
      "review_date": ISODate('2024-06-08T09:45:18.890Z'),
      "rating": 3,
      "comment": "Average quality"
    }
  ],
  "material": "Polycarbonate",
  "color": "Space Gray",
  "supplier": {
    "supplierId": "SUP4",
    "location": {
      "type": "Point",
      "coordinates": [ -71.0589, 42.3601 ]
    }
  },
  "productEmbedding": [
    -0.019320633663838058,
    0.019672111388113596
  ],
  "lastUpdated": ISODate('2025-10-20T21:37:10.585Z')
}
```

**单字段**

在 LastUpdated 上创建 TTL 索引以删除在 90 天内未更新的文档：

```
db.collection.createIndex(
  {
    "lastUpdated": 1
  },
  {
    "name": "lastUpdated_ttl",
    "expireAfterSeconds": 7776000
  }
)
```

**多键**

在 reviews.review\_date 上创建 TTL 索引，以删除在过去一年中没有评论的文档：

```
db.collection.createIndex(
  {
    "reviews.review_date": 1
  },
  {
    "name": "reviews_review_date_ttl",
    "expireAfterSeconds": 31536000
  }
)
```

请注意，如果 TTL 索引位于数组字段上，则会检查数组中的所有项目。如果数组中的任何时间戳满足超时条件，则该文档将被删除。