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

相关推荐
Y3815326624 小时前
MySQL 慢查询排查实战:EXPLAIN 看懂 type 与 Extra,一个字段定位性能问题
数据库·mysql
Logintern095 小时前
PostgreSQL 的 ORDER BY 多列排序
数据库·postgresql
今天AI了吗6 小时前
DeepSeek Harness 深度解析:从评测架构到实战落地
java·网络·数据库·人工智能·架构·java-ee
数据库小学妹6 小时前
为什么MySQL索引用B+树?从存储底层讲透原理
数据库·mysql·b+树·索引优化·磁盘io·数据库原理
BestHeaker6 小时前
制造业 MES 开发入门:和互联网业务开发的 5 个本质差异(一)
数据库·经验分享·制造业·mes
自动化监测Learner7 小时前
Navicat Premium 17 中文版安装教程(2026最新版)
java·linux·数据库
张文是假的啊7 小时前
常用JPA注解解释
数据库
Allen_LVyingbo9 小时前
医疗AI基础2026-构建可靠智能体的编程路径(上)
大数据·数据库·人工智能·python·自动化
疯狂打码的少年9 小时前
【数据库技术】多值依赖与第四范式(4NF)
数据库·笔记·算法