You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
40 lines
1.0 KiB
Go
40 lines
1.0 KiB
Go
package model
|
|
|
|
import (
|
|
"context"
|
|
"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 IncId struct {
|
|
ID primitive.ObjectID `json:"_id" bson:"_id"`
|
|
Key string `json:"key" bson:"key"`
|
|
IncId int `json:"inc_id" bson:"inc_id"`
|
|
}
|
|
|
|
func GetId(collection *mongo.Collection, key string, inc int) (int64, error) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
filter := bson.D{{Key: "key", Value: key}}
|
|
update := bson.D{{Key: "$set", Value: bson.D{{Key: "key", Value: key}}}, {Key: "$inc", Value: bson.D{{Key: "inc_id", Value: inc}}}}
|
|
upsert := true
|
|
opts := options.UpdateOptions{
|
|
Upsert: &upsert,
|
|
}
|
|
_, err := collection.UpdateOne(ctx, filter, update, &opts)
|
|
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
var result IncId
|
|
err1 := collection.FindOne(ctx, filter).Decode(&result)
|
|
if err1 != nil {
|
|
return 0, err
|
|
}
|
|
return int64(result.IncId), nil
|
|
}
|