Home >Backend Development >Golang >How to Ensure Document Expiration in MongoDB Using Go-Mongo-Driver?

How to Ensure Document Expiration in MongoDB Using Go-Mongo-Driver?

Susan Sarandon
Susan SarandonOriginal
2024-10-29 22:15:041036browse

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!

Statement:
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