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)
	}
}
發佈了75 篇原創文章 · 獲贊 44 · 訪問量 24萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章