"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Aren\'t My MongoDB Documents Expiring After 5 Seconds with TTL Indexes in Go?

Why Aren\'t My MongoDB Documents Expiring After 5 Seconds with TTL Indexes in Go?

Published on 2024-11-07
Browse:340

Why Aren\'t My MongoDB Documents Expiring After 5 Seconds with TTL Indexes in Go?

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:

  • Create an index with an expireAfterSeconds option
  • Insert sample data with varying creation timestamps

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.

Latest tutorial More>

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