Home > Backend Development > Golang > How to Set Up Automatic Document Expiration in MongoDB with Go?

How to Set Up Automatic Document Expiration in MongoDB with Go?

Mary-Kate Olsen
Release: 2024-10-29 17:24:02
Original
367 people have browsed it

How to Set Up Automatic Document Expiration in MongoDB with Go?

Expiring Documents in MongoDB After a Fixed Time Interval

In Go, using the mongo-go-driver, you can automatically expire documents in a collection based on a specified number of seconds.

Explanation

For documents to expire automatically, you need to:

  1. Create an index with the expireAfterSeconds option: This sets the TTL (time to live) of documents based on a field (e.g., createdAt).
  2. Insert documents with the specified timestamp field: When inserting documents, ensure they have the createdAt field to determine when the TTL starts.

Example Code

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>
Copy after login

Note about Timing

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template