Golang 中 MongoDB 实现 MySQL 自动递增 AUTO_INCREMENT

大致思路就是为每一个需要自动递增的表创建辅助表记录当前编号,每次插入前总会原子的去辅助表中查且修改当前编号

本文不考虑该实现的广泛可用性(集群时可能无法使用此方案)

思路不限制编程语言,但这里提供 Golang 的实现

package main

import (
	"context"
	"log"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

// exec this before run
// db.message_id.insert({id: 1});

var mgo *mongo.Database

// InsertOneEx .
func InsertOneEx(collection string, document map[string]interface{}) (*mongo.InsertOneResult, error) {
	if err := mgo.Collection(collection+"_id").FindOneAndUpdate(context.Background(), bson.M{}, bson.M{"$inc": bson.M{"id": 1}}, &options.FindOneAndUpdateOptions{Projection: bson.M{"_id": 0}}).Decode(&document); err != nil {
		return nil, err
	}
	return mgo.Collection(collection).InsertOne(context.Background(), document)
}

func main() {
	client, err := mongo.Connect(context.Background(), options.Client().ApplyURI("mongodb://127.0.0.1/panshiqu"))
	if err != nil {
		log.Fatal(err)
	}

	mgo = client.Database("panshiqu")

	if res, err := InsertOneEx("message", bson.M{"content": "hello"}); err == nil {
		log.Println(res.InsertedID)
	} else {
		log.Fatal(err)
	}
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值