

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 索引屬性： expireAfterSeconds
<a name="index-property-expireafterseconds"></a>

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


| 索引類型 | 3.6 | 4.0 | 5.0 | 8.0 | 彈性叢集 | 
| --- | --- | --- | --- | --- | --- | 
| 單一欄位 | 是 | 是 | 是 | 是 | 是 | 
| 多金鑰 | 是 | 是 | 是 | 是 | 是 | 

使用 expireAfterSeconds 選項來建立存留時間 (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
  }
)
```

**多金鑰**

在 review.review\_date 上建立 TTL 索引，以刪除過去一年沒有檢閱的文件：

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

請注意，如果 TTL 索引位於陣列欄位上，則會檢查陣列中的所有項目。如果陣列中的任何時間戳記符合逾時條件，則會刪除文件。