Golang调用MongoDB的表自动增长的 ID 永久保存在 MongoDB 中,并且每次获取的 ID 是基于上次的结果

以下是使用 MongoDB 的原子操作来实现自动增长 ID 并永久保存的方法:

Go 复制代码
package main

import (
    "context"
    "fmt"
    "log"
    "time"

    "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"
)

type Counter struct {
    ID    string `bson:"_id"`
    Value int    `bson:"value"`
}

func getNextID(ctx context.Context, collection *mongo.Collection) (int, error) {
    update := bson.M{
        "$inc": bson.M{"value": 1},
    }
    upsert := true
    after := options.After
    opt := options.FindOneAndUpdateOptions{
        Upsert:         &upsert,
        ReturnDocument: &after,
    }
    var counter Counter
    err := collection.FindOneAndUpdate(ctx, bson.M{"_id": "documentIdCounter"}, update, &opt).Decode(&counter)
    if err!= nil {
        return 0, err
    }
    return counter.Value, nil
}

func main() {
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
    client, err := mongo.Connect(context.TODO(), clientOptions)
    if err!= nil {
        log.Fatal(err)
    }
    defer client.Disconnect(context.TODO())

    collection := client.Database("testdb").Collection("counters")

    for i := 0; i < 5; i++ {
        id, err := getNextID(context.TODO(), collection)
        if err!= nil {
            log.Fatal(err)
        }
        fmt.Println("Generated ID:", id)
        time.Sleep(time.Second)
    }
}

在这个示例中:

  • 定义了一个Counter结构体来表示存储自动增长 ID 的文档结构。
  • getNextID函数使用FindOneAndUpdate方法来原子性地增加计数器的值,并返回新的 ID。如果计数器文档不存在,会自动创建并初始化为 1。
  • 在主函数中,循环调用getNextID函数生成多个 ID,并打印出来。

这样可以确保自动增长的 ID 永久保存在 MongoDB 中,并且每次获取的 ID 是基于上次的结果。

相关推荐
AOwhisky3 小时前
MySQL 学习笔记(第四期):SQL 语言之多表查询
linux·运维·网络·数据库·笔记·学习·mysql
小红卒3 小时前
mysql之udf提权
数据库·mysql·网络安全
Trouvaille ~4 小时前
【Redis篇】Redis 哨兵(Sentinel):高可用自动故障转移
数据库·redis·缓存·中间件·sentinel·高可用·哨兵
qfljg4 小时前
oracle 迁移到postgres
数据库·oracle
giaz14n9X4 小时前
Redis 分布式锁进阶第五十七篇
数据库·redis·分布式
剑神一笑5 小时前
Linux ls 命令深度解析:从目录遍历到颜色输出的实现原理
linux·服务器·数据库
Maynor9965 小时前
Codex API 网关迁移与流量优化实战
数据库·oracle
WyCAGy8ij5 小时前
Redis 分布式锁进阶第二篇讲解
数据库·redis·分布式
南极企鹅5 小时前
MySQL的两大支柱:undo Log&redo log
数据库·mysql·oracle
智航GIS5 小时前
ArcGIS大师之路500技---078文件数据库的加密与解密
数据库·arcgis