How to Ensure Document Expiration in MongoDB Using Go-Mongo-Driver?
Expiring Documents After a Specified Period in Golang Using Mongo
In Golang, mongo-go-driver provides the capability to automatically expire documents after a specified number of seconds. However, some users may encounter issues with this feature not functioning as intended.
To resolve this, it is crucial to adhere to the correct procedure for creating an expireAfterSeconds index. This involves setting up a TTL (Time-to-Live) index that determines the time period after which a document should be deleted.
Example Code for Expiring Documents
<code class="golang">package main import ( "context" "fmt" "log" "time" "github.com/Pallinder/go-randomdata" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) func main() { ctx := context.TODO() client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017")) if err != nil { log.Fatal(err) } err = client.Connect(ctx) if err != nil { log.Fatal(err) } db := client.Database("LADB") col := db.Collection("LACOLL") // Add an index to the collection with an expireAfterSeconds option model := mongo.IndexModel{ Keys: bson.M{"createdAt": 1}, Options: options.Index().SetExpireAfterSeconds(1), } ind, err := col.Indexes().CreateOne(ctx, model) if err != nil { log.Fatal(err) } fmt.Println(ind) // Insert some documents with createdAt timestamp for i := 0; i < 5; i++ { name := randomdata.SillyName() res, err := col.InsertOne(ctx, NFT{Timestamp: time.Now(), CreatedAt: time.Now(), Name: name}) if err != nil { log.Fatal(err) } fmt.Println("Inserted", name, "with ID", res.InsertedID) time.Sleep(1 * time.Second) } // Find all documents in the collection cursor, err := col.Find(ctx, bson.M{}, nil) if err != nil { log.Fatal(err) } var datas []NFT if err = cursor.All(ctx, &datas); err != nil { log.Fatal(err) } // Note that there may be a delay in deleting expired documents (up to 60 seconds) fmt.Println(datas) } type NFT struct { ID primitive.ObjectID `bson:"_id,omitempty"` CreatedAt time.Time `bson:"createdAt,omitempty"` Timestamp time.Time `bson:"timestamp,omitempty"` Name string `bson:"name,omitempty"` }</code>
Note: MongoDB's background task for removing expired documents runs every 60 seconds. Therefore, there may be a delay in deleting expired documents, potentially up to 60 seconds.
The above is the detailed content of How to Ensure Document Expiration in MongoDB Using Go-Mongo-Driver?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

Under the BeegoORM framework, how to specify the database associated with the model? Many Beego projects require multiple databases to be operated simultaneously. When using Beego...

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...
