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

相关推荐
5***E6859 小时前
【SQL】写SQL查询时,常用到的日期函数
数据库·sql
遇见火星9 小时前
CentOS7 通过源码安装 Redis
数据库·redis·缓存
Mr.朱鹏9 小时前
RocketMQ安装与部署指南
java·数据库·spring·oracle·maven·rocketmq·seata
Coder-coco9 小时前
个人健康管理|基于springboot+vue+个人健康管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·mysql·论文
K哥11259 小时前
【9天Redis系列】基础+全局命令
数据库·redis·缓存
s***46989 小时前
【玩转全栈】----Django模板语法、请求与响应
数据库·python·django
f***R810 小时前
redis分页查询
数据库·redis·缓存
g***727010 小时前
【mysql】导出导入mysql表结构或者数据
数据库·mysql
煎蛋学姐10 小时前
SSM汽车租赁管理系统mfobv(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面
数据库·汽车·ssm 框架·汽车租赁管理系统
w***375110 小时前
Spring 核心技术解析【纯干货版】- Ⅶ:Spring 切面编程模块 Spring-Instrument 模块精讲
前端·数据库·spring