根据文档,go.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"}
。
当没有提供 ID 时,是否有一种自动递增 ID 的干净方法mongo-driver
,而无需自己执行跟踪最后一个 ID 的逻辑?假设数据库中已经有 5 个文档,那么在{"_id":6,"foo":"test"}
没有提供 ID 时运行上面的代码将持续存在。