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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3