> For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

# Expire Data from Collections by Setting TTL

This document provides an introduction to MongoDB's "*time to live*" or [TTL](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-TTL) collection feature. TTL collections make it possible to store data in MongoDB and have the [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) automatically remove data after a specified number of seconds or at a specific clock time.

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](https://www.mongodb.com/docs/manual/core/index-ttl.md#std-label-index-feature-ttl) supports the implementation of TTL collections. The TTL feature relies on a background thread in [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) that reads the date-typed values in the index and removes expired [documents](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-document) from the collection.

To create a TTL index, use [`createIndex()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.createindex.md#mongodb-method-db.collection.createIndex). Specify an index field that is either a [date type](https://www.mongodb.com/docs/manual/reference/bson-types.md#std-label-document-bson-type-date) or an array that contains date type values. Use the `expireAfterSeconds` option to specify a TTL value in seconds.

**Note:**

The TTL index is a single field index. Compound indexes do not support the TTL property. For more information on TTL indexes, see [TTL Indexes.](https://www.mongodb.com/docs/manual/core/index-ttl.md#std-label-index-feature-ttl)

You can modify the `expireAfterSeconds` of an existing TTL index using the [`collMod`](https://www.mongodb.com/docs/manual/reference/command/collmod.md#mongodb-dbcommand-dbcmd.collMod) command.

## Expire Documents in the MongoDB Atlas UI

To expire data in the [Atlas UI](https://www.mongodb.com/docs/atlas/atlas-ui.md#std-label-atlas-ui-overview), follow these steps:

1. In the MongoDB Atlas UI, go to the Clusters page for your project.

   If it's not already displayed, select the organization that contains your desired project from the  Organizations menu in the navigation bar.

   If it's not already displayed, select your project from the Projects menu in the navigation bar.

   In the sidebar, click Clusters under the Database heading.

   The [Clusters](https://cloud.mongodb.com/go?l=https%3A%2F%2Fcloud.mongodb.com%2Fv2%2F%3Cproject%3E%23%2Fclusters) page displays.

2. Navigate to the collection

   For the cluster that contains the data you want to expire, click Browse Collections.

   In the left navigation pane, select the database.

   In the left navigation pane, select the collection.

3. Open the Create Index modal

   Click the Indexes tab.

   Click Create Index.

4. Create the index with the `expiresAfterSeconds` option

   In the Fields section, enter the index key specification document. For this example, enter the following text to create an index on the `expiresAfter` field:

   ```text
   { "expiresAfter": 1 }
   ```

   In the Options section, enter the `expireAfterSeconds` option. For this example, enter the following text to expire the data 1 second after the `expiresAfter` field's value:

   ```text
   { expireAfterSeconds: 1 }
   ```

   Click Review.

   Click Confirm.

5. Add a document that contains the `expiresAfter` field to the collection

   In the left navigation pane, select the collection that contains the index.

   Click the Find tab.

   Click Insert Document.

   Click the text field under the \_id field and enter the field name `expiresAfter`.

   Click the text field next to `expiresAfter` and enter the following value:

   ```text
   2023-10-01T12:00:00.000+00:00
   ```

   This value expires data after 12:00 on October 1, 2023.

   Click the data type drop-down menu and change the data type value to Date.

   Click Insert.

   The document expires automatically one second after the `expiresAfter` field's value.

   The TTL index may take one to two seconds to expire the document. You may need to refresh the UI to see that MongoDB Atlas deletes the expired document.

## Expire Documents after a Specified Number of Seconds

You can expire documents after a specified number of seconds through collection creation options or a TTL index.

### Specify Expiration at Collection Creation

To specify expiration time at collection creation, use the [expireAfterSeconds](https://www.mongodb.com/docs/manual/reference/method/db.createcollection.md#std-label-db.createCollection.expireAfterSeconds) option when you create your collection.

**Note:**

The `expireAfterSeconds` option is only available for [time series collections](https://www.mongodb.com/docs/manual/core/timeseries-collections.md#std-label-manual-timeseries-landing) and [clustered collections.](https://www.mongodb.com/docs/manual/core/clustered-collections.md#std-label-clustered-collections)

### Specify Expiration with a TTL Index

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 value greater than or equal to zero in the `expireAfterSeconds` field. A document expires when the number of seconds in the `expireAfterSeconds` field has passed since the time specified in its indexed field.&#x20;

The TTL index `expireAfterSeconds` value must be within `0` and `2147483647` inclusive.

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`.

```javascript
db.log_events.createIndex( { "createdAt": 1 }, { expireAfterSeconds: 10 } )
```

When adding documents to the `log_events` collection, set the `createdAt` field to the current time:

```javascript
db.log_events.insertOne( {
   "createdAt": new Date(),
   "logEvent": 2,
   "logMessage": "Success!"
} )
```

MongoDB automatically deletes documents from the `log_events` collection when the document's `createdAt` value  is older than the number of seconds specified in `expireAfterSeconds`.

If the field contains an array of BSON date-typed objects, data expires if at least one of BSON date-typed object is older than the number of seconds specified in `expireAfterSeconds`.

## Expire Documents with Filter Conditions

To expire documents with specific filter expressions, you can create an index that is both a [partial](https://www.mongodb.com/docs/manual/core/index-partial.md#std-label-index-type-partial) and a [TTL](https://www.mongodb.com/docs/manual/core/index-ttl.md#std-label-index-feature-ttl) index.

Create a partial TTL index:

```javascript
db.events.createIndex(
   { createdAt: 1 },
   {
      name: "Partial-TTL-Index",
      partialFilterExpression: { type: "click" },
      expireAfterSeconds: 10
   }
)

```

Insert two documents, one of which matches the filter expression `{ type: "click" }` of the `partialFilterExpression`:

```javascript
db.events.insertMany( [
   { createdAt: new Date(), type: "view" },
   { createdAt: new Date(), type: "click" }
] )

```

Wait for the TTL background thread to run, then query the `events` collection:

```javascript
db.events.find( {}, { _id: 0, type: 1 } )
```

MongoDB deletes (expires) the document that matches the `partialFilterExpression` of `{ type: "click" }`. As a result, only the document that does not match the filter remains:

```javascript
{ type: "view" }
```

## Expire Documents at a Specific Clock Time

To expire documents at a specific clock time, create a TTL index on a field that holds values of BSON date type or an array of BSON date-typed objects, and specify an `expireAfterSeconds` value of `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.

For example, the following operation creates an index on the `log_events` collection's `expireAt` field and specifies the `expireAfterSeconds` value of `0`:

```javascript
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. For example, the following [`insertOne()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.insertone.md#mongodb-method-db.collection.insertOne) operation adds a document that expires at `July 22, 2013 14:00:00`.

```javascript
db.log_events.insertOne( {
   "expireAt": new Date('July 22, 2013 14:00:00'),
   "logEvent": 2,
   "logMessage": "Success!"
} )
```

MongoDB automatically deletes documents from the `log_events` collection when the documents' `expireAt` value is older than the number of seconds specified in `expireAfterSeconds`, that is, `0` seconds older in this case.

## Indexes Configured Using NaN

**Warning:**

Possible Data Loss

When a TTL index has `expireAfterSeconds` set to `NaN`, upgrade, downgrade, and certain syncing operations can lead to unexpected behavior and possible data loss.

Do not set `expireAfterSeconds` to `NaN` in your TTL index configuration.

Prior to MongoDB 5.0, when a TTL index has `expireAfterSeconds` set to `NaN`, MongoDB logs an error and does not remove any records.

From MongoDB 5.0.0 - 5.0.13 (and 6.0.0 - 6.0.1), `NaN` is treated as `0`. If a TTL index is configured with `expireAfterSeconds` set to `NaN`, all TTL-indexed documents expire immediately.

Starting in MongoDB 5.0.14 (and 6.0.2), the server will not use TTL indexes that have `expireAfterSeconds` set to `NaN`.

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).

- When upgrading from an earlier version to MongoDB 5.0.0 - 5.0.13.

- When restoring a collection from a pre-5.0 [`mongodump`](https://www.mongodb.com/docs/database-tools/mongodump.md#mongodb-binary-bin.mongodump) into a MongoDB 5.0.0 - 5.0.13 (or 6.0.0 - 6.0.1) instance.

To avoid problems, either drop or correct any misconfigured TTL indexes.

1. Identify misconfigured indexes.

   Run the following script in the [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh) shell. The script does not work in the legacy `mongo` shell.

   ```javascript
   function getNaNIndexes() {
      const nan_index = [];

      const dbs = db.adminCommand({ listDatabases: 1 }).databases;

      dbs.forEach((d) => {
         if (d.name != 'local') {
            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();
   ```

2. Correct misconfigured indexes.

   Use the [`collMod`](https://www.mongodb.com/docs/manual/reference/command/collmod.md#mongodb-dbcommand-dbcmd.collMod) command to update any misconfigured `expireAfterSeconds` values that the script found.

   As an alternative, you can [`drop`](https://www.mongodb.com/docs/manual/reference/command/dropindexes.md#mongodb-dbcommand-dbcmd.dropIndexes) any misconfigured TTL indexes and recreate them later using the [`createIndexes`](https://www.mongodb.com/docs/manual/reference/command/createindexes.md#mongodb-dbcommand-dbcmd.createIndexes) command.
