带有Golang mongo驱动程序的MongoDB自动增量ID

问题描述 投票:0回答:1

基于documentationgo.mongodb.org/mongo-driver似乎在提供未提供ID的文档时为自动增加ID提供一种方法。

    type Document struct {
        ID             int    `bson:"_id"`
        Foo            string `bson:"foo"`
    }

    document := &Document{Foo: "test"}

    filter := bson.M{"_id": bson.M{"$eq": document.ID}}
    update := bson.M{"$set": document}

    res, err := mongoClient.Database(dbName).
        Collection(collectionName).
        UpdateOne(ctx, filter, update,
            options.Update().SetUpsert(true))

在上面的代码示例中,ID将默认为int的零值,即0,并将在MongoDB中保留为{"_id":0,"foo":"test"}

如果没有使用mongo-driver来提供ID,而没有自己跟踪最后一个ID的逻辑,是否有一种自动递增ID的干净方法?例如,假设数据库中已经有5个文档,那么当不提供ID时,运行上述代码将持续{"_id":6,"foo":"test"}

mongodb go auto-increment id mongo-go
1个回答
0
投票

我发现了同样的问题,我认为解决方案是定义没有ID的Document结构:

type Document struct {
    Foo string `bson:"foo"`
}

然后,如果使用mongo-driver执行InsertOne操作:

res, err := mongoClient.Database(dbName).Collection(collectionName).InsertOne(ctx, document)

<< [_ id将在数据库中自动创建(您可以重复执行InsertOne次,新的_ id将会出现)。

mongodb文档解释了此行为:

“如果文档未指定_id字段,则mongod将添加_id字段并为文档分配唯一的ObjectId,然后再插入。”(您可以在中阅读更多详细信息https://docs.mongodb.com/manual/reference/method/db.collection.insertOne/#db.collection.insertOne

如果出于某种原因需要新创建的

_ id

,则可以使用以下代码段作为参考来检索它:fmt.Println("New Document created with mongodb _id: " + res.InsertedID.(primitive.ObjectID).Hex())

primitive.ObjectID

与此相关:导入“ go.mongodb.org/mongo-driver/bson/primitive”)希望这会有所帮助!
© www.soinside.com 2019 - 2024. All rights reserved.