In Go, using the mongo-go-driver, you can automatically expire documents in a collection based on a specified number of seconds.
For documents to expire automatically, you need to:
In your Go code:
<code class="go">// Add an index to expire documents after 1 second (for testing purposes). model := mongo.IndexModel{ Keys: bson.M{"createdAt": 1}, Options: options.Index().SetExpireAfterSeconds(1), } ind, err := col.Indexes().CreateOne(ctx, model)</code>
It's important to note that the expireAfterSeconds option specifies the duration after which a document is eligible for deletion. However, the actual deletion may not happen immediately.
MongoDB runs a background task every 60 seconds to remove expired documents. Therefore, expired documents may remain in the collection for up to 60 seconds after their TTL expires. Additionally, if the database is under heavy load, the deletion process may take longer.
Keep this in mind when expecting your documents to be deleted promptly.
The above is the detailed content of How to Set Up Automatic Document Expiration in MongoDB with Go?. For more information, please follow other related articles on the PHP Chinese website!