Articles → MONGODB → Time To Live Index In Mongodb

Time To Live Index In Mongodb






Purpose





Syntax


db.collection.createIndex(
  { "date_field_name": 1 }, 
  { expireAfterSeconds: [number_of_seconds] }
);



Example




Picture showing the sample document collection




db.Sessions.createIndex(
  { "createdAt": 1 }, 
  { expireAfterSeconds: 1 }
);


Picture showing creating the time to live index in mongodb



Output


Picture showing the document is deleted after the specified expired time



Posted By  -  Karan Gupta
 
Posted On  -  Friday, May 3, 2024

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250