Expire Data from Collections by Setting TTL (2024)

Docs Home

/

MongoDB Manual

/

Indexes

/

Properties

/

TTL

On this page

  • Expire Documents in the MongoDB Atlas UI
  • Expire Documents after a Specified Number of Seconds
  • Expire Documents with Filter Conditions
  • Expire Documents at a Specific Clock Time
  • Indexes Configured Using NaN

This document provides an introduction to MongoDB's "time to live"or TTL collection feature. TTL collections make it possible tostore data in MongoDB and have the mongod automaticallyremove data after a specified number of seconds or at a specific clocktime.

You can expire data for deployments hosted in the followingenvironments:

  • MongoDB Atlas: The fullymanaged service for MongoDB deployments in the cloud

  • MongoDB Enterprise: Thesubscription-based, self-managed version of MongoDB

  • MongoDB Community: Thesource-available, free-to-use, and self-managed version of MongoDB

Data expiration is useful for some classes of information, includingmachine generated event data, logs, and session information that onlyneed to persist for a limited period of time.

A special TTL index property supports theimplementation of TTL collections. The TTL feature relies on abackground thread in mongod that reads the date-typed valuesin the index and removes expired documents from thecollection.

To create a TTL index, use 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.

Note

The TTL index is a single field index. Compound indexes do notsupport the TTL property. For more information on TTL indexes, seeTTL Indexes.

You can modify the expireAfterSeconds of an existing TTL indexusing the collMod command.

If a time series collection contains documents with timeFieldtimestamps before 1970-01-01T00:00:00.000Z or after2038-01-19T03:14:07.000Z, no documents are deleted from thecollection by the TTL "time to live" feature.

Expire Documents in the MongoDB Atlas UI

To expire data in the Atlas UI, followthese steps:

1

Navigate to the collection

  1. In the MongoDB Atlas UI, click Database in the sidebar.

  2. For the database deployment that contains the data you want toexpire, click Browse Collections.

  3. In the left navigation pane, select the database.

  4. In the left navigation pane, select the collection.

2

Open the Create Index modal

  1. Click the Indexes tab.

  2. Click Create Index.

3

Create the index with the expiresAfterSeconds option

  1. In the Fields section, enter the index keyspecification document. For this example, enter thefollowing text to create an index on theexpiresAfter field:

    { "expiresAfter": 1 }

  2. In the Options section, enter theexpireAfterSeconds option. For this example, enter thefollowing text to expire the data 1 second after theexpiresAfter field's value:

    { expireAfterSeconds: 1 }

  3. Click Review.

  4. Click Confirm.

4

Add a document that contains the expiresAfter field to the collection

  1. In the left navigation pane, select the collection thatcontains the index.

  2. Click the Find tab.

  3. Click Insert Document.

  4. Click the text field under the _id field and enterthe field name expiresAfter.

  5. Click the text field next to expiresAfter and enter thefollowing value:

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

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

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

  7. Click Insert.

    The document will expire automatically one second after theexpiredAfter field's value.

    The TTL index may take 1-2 seconds to expire the document.You may need to refresh the UI to see that MongoDB Atlas deletesthe expired document.

Expire Documents after a Specified Number of Seconds

You can expire data after a specified number of seconds in the terminal.To expire data after a specified number of seconds has passed since theindexed field, create a TTL index on a field that holds values of BSONdate type or an array of BSON date-typed objects and specify apositive non-zero value in the expireAfterSeconds field. A documentwill expire when the number of seconds in the expireAfterSecondsfield has passed since the time specified in its indexed field.[1]

The TTL index expireAfterSeconds value must be within 0 and2147483647 inclusive.

For example, the following operation creates an index on thelog_events collection's createdAt field and specifies theexpireAfterSeconds value of 10 to set the expiration time tobe ten seconds after the time specified by createdAt.

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

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

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

MongoDB will automatically delete documents from the log_eventscollection when the document's createdAt value[1] is older than the number of secondsspecified in expireAfterSeconds.

[1](1, 2) If the field contains an array of BSONdate-typed objects, data expires if at least one of BSON date-typedobject is older than the number of seconds specified inexpireAfterSeconds.

Expire Documents with Filter Conditions

To expire documents with specific filter expressions, you can createan index that is both a partialand a TTL index.

Create a partial TTL index:

db.foo.createIndex(
{ F: 1 },
{
name: "Partial-TTL-Index",
partialFilterExpression: { D : 1 },
expireAfterSeconds: 10
}
)

Insert two documents, one of which matches the filter expression{ D : 1 } of the partialFilterExpression:

db.foo.insertMany( [
{ "F" : ISODate("2019-03-07T20:59:18.428Z"), "D" : 3},
{ "F" : ISODate("2019-03-07T20:59:18.428Z"), "D" : 1}
] )

Wait for ten seconds then query the foo collection:

db.foo.find({}, {_id: 0, F: 1, D: 1})

The document that matches the partialFilterExpressionof { D : 1 } is deleted (expired). As a result, onlyone document remains in the foo collection:

{ "F" : ISODate("2019-03-07T20:59:18.428Z"), "D" : 3}

Expire Documents at a Specific Clock Time

You can expire data at a specified clock time in the terminal. Toexpire documents at a specific clock time, begin by creating a TTLindex on a field that holds values of BSON date type or an array ofBSON date-typed objects and specify an expireAfterSeconds valueof 0. For each document in the collection, set the indexed datefield to a value corresponding to the time the document should expire.If the indexed date field contains a date in the past, MongoDBconsiders the document expired.

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

db.log_events.createIndex( { "expireAt": 1 }, { expireAfterSeconds: 0 } )

For each document, set the value of expireAt to correspond to thetime the document should expire. For example, the followinginsertOne() operation adds a document thatexpires at 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_eventscollection when the documents' expireAt value is older than thenumber of seconds specified in expireAfterSeconds, i.e. 0seconds older in this case. As such, the data expires at the specifiedexpireAt value.

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 unexpectedbehavior and possible data loss.

Do not set expireAfterSeconds to NaN in your TTL indexconfiguration.

Prior to MongoDB 5.0, when a TTL index has expireAfterSeconds set toNaN, 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 as0. If a TTL index is configured with expireAfterSeconds set toNaN, all TTL-indexed documents expire immediately.

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

However, there are still some situations which may result in unexpectedbehavior. 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 mongodumpinto 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 shell. Thescript does not work in the legacy mongo shell.

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 command to update any misconfiguredexpireAfterSeconds values that the script found.

As an alternative, you can drop anymisconfigured TTL indexes and recreate them later using thecreateIndexes command.

BackTTLNextUnique
Expire Data from Collections by Setting TTL (2024)
Top Articles
Gulf Coast Grand Slam Global World Series Week 2 (2024) - Gulfport, MS - USSSA Mississippi Baseball
2024 11U PG Gulf Coast World Series (Gulf Shores
The Civil Rights Movement: A Very Short Introduction
Sarah Burton Is Givenchy's New Creative Director
W B Crumel Funeral Home Obituaries
Culver's Flavor Of The Day Ann Arbor
Gameplay Clarkston
Ascension St. Vincent's Lung Institute - Riverside
Celebrity Guest Tape Free
Guardians Of The Galaxy Showtimes Near Athol Cinemas 8
Ups Drop Off Newton Ks
11 Best Sites Like The Chive For Funny Pictures and Memes
Creepshot. Org
Arre St Wv Srj
Lkq Pull-A-Part
Best Fantasy Basketball Team
Trailmaster Fahrwerk - nivatechnik.de
Rice explains personal reason for subdued goal celebration against Ireland
Rooms for rent in Pompano Beach, Broward County, FL
Noah Schnapp Lpsg
Lake Charles, LA Houses and Single Family Homes For Rent | realtor.com®
Kimpton Hotels In Charleston Sc
Maya Mixon Portnoy
Craigslist Pets Peoria Il
Katmoie
Skyward Weatherford Isd Login
Www.burlingtonfreepress.com Obituaries
Enloe Bell Schedule
55000 Pennies To Dollars
What Time Does The Moon Rise At My Location
Naydenov Gymnastics Reviews
Ktbs Payroll Login
Cric7.Net Ipl 2023
Vip Market Vetsource
Umbc Registrar
Wolf Of Wallstreet 123 Movies
Craigs List Waco
Costco Gasoline and Sam's Club Fuel Center Gas Savings - Consumer Reports
Www.playgd.mobi Wallet
Odawa Hypixel
100K NOTES - [DEEPWOKEN - DEEP WOKEN - ROBLOX] | ID 217435304 | PlayerAuctions
Mike Norvell Height
Acbl Homeport
Burkes Outlet Credit Card Sign In
Gtl Visit Me Alameda
The forgotten history of cats in the navy
La Fitness North Wales Class Schedule
Hotels Near William Woollett Jr Aquatics Center
El Pulpo Auto Parts Houston
Raleigh Craigs List
Codex Genestealer Cults 10th Edition: The Goonhammer Review
Ticketmaster Lion King Chicago
Latest Posts
Article information

Author: Kieth Sipes

Last Updated:

Views: 6476

Rating: 4.7 / 5 (47 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Kieth Sipes

Birthday: 2001-04-14

Address: Suite 492 62479 Champlin Loop, South Catrice, MS 57271

Phone: +9663362133320

Job: District Sales Analyst

Hobby: Digital arts, Dance, Ghost hunting, Worldbuilding, Kayaking, Table tennis, 3D printing

Introduction: My name is Kieth Sipes, I am a zany, rich, courageous, powerful, faithful, jolly, excited person who loves writing and wants to share my knowledge and understanding with you.