Using MongoDB Expire Documents After a Specified Number of Seconds in Go
Using TTL indexes, MongoDB allows you to automatically expire documents after a specified duration. This article demonstrates how to achieve this in Go using the official mongo-go-driver.
Following the MongoDB documentation, the code shows how to:
However, the provided example is performing correctly, and the issue is not related to the code.
Understanding TTL Index Behavior
The expireAfterSeconds parameter specifies the duration after the createdAt field when the document should be considered expired. However, the deletion of expired documents is not immediate.
According to MongoDB documentation:
"The TTL index does not guarantee that expired data will be deleted immediately upon expiration. There may be a delay between the time a document expires and the time that MongoDB removes the document from the database."
Background Task for Deletion
MongoDB has a background task that removes expired documents every 60 seconds. Therefore, documents may remain in the collection for up to 60 seconds after expiring. Furthermore, if the database is under heavy load, it may take additional time for all expired documents to be deleted.
Resolution
In your code snippet, you expect some documents to be deleted after 5 seconds (based on the expireAfterSeconds option) but only wait seconds after insertion for verification. To correctly test the functionality, you should allow sufficient time (several minutes at minimum) for the background task to run and delete the expired documents.
The above is the detailed content of Why Aren\'t My MongoDB Documents Expiring After 5 Seconds with TTL Indexes in Go?. For more information, please follow other related articles on the PHP Chinese website!