Based on the documentation, go.mongodb.org/mongo-driver
doesn't seem to provide a way to auto-increment ID when it is upserting a document that has not provided an 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))
In the code example above, ID will be defaulted to the zero value of int, which is 0
, and will be persisted in MongoDB as {"_id":0,"foo":"test"}
.
Is there a clean way for auto-incrementing ID when ID is not provided using mongo-driver
, without doing the logic of tracking the last ID myself? Say for example there are already 5 documents in the DB, then running the code above will persist {"_id":6,"foo":"test"}
when ID is not provided.