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 是基于上次的结果。

相关推荐
星星也在雾里6 小时前
PgBouncer 解决 PostgreSQL 连接数超限 + 可视化监控
数据库·postgresql
雨辰AI7 小时前
SpringBoot3 + 人大金仓读写分离 + 分库分表 + 集群高可用 全栈实战
java·数据库·mysql·政务
长城20248 小时前
关于MySql的ONLY_FULL_GROUP_BY问题
数据库·mysql·聚合列
常常有8 小时前
MySQL 底层执行原理:输入SQL语句到两阶段提交
数据库·sql·mysql
Mr. zhihao8 小时前
深入解析redis基本数据结构
数据结构·数据库·redis
m0_748839499 小时前
利用天正暖通CAD快速掌握风管数量统计的方法
数据库
随身数智备忘录9 小时前
什么是设备管理体系?设备管理体系包含哪些核心模块?
网络·数据库·人工智能
海市公约9 小时前
MySQL更新语句执行全流程:从Buffer Pool修改到二阶段提交
数据库·mysql·binlog·innodb·undo log·二阶段提交·update执行原理
颂love10 小时前
MySQL的执行流程
android·数据库·mysql
程序leo源10 小时前
Qt窗口详解
开发语言·数据库·c++·qt·青少年编程·c#