I am new to mongodb and golang. In one of my project i want to connect mongo with go. I am using mgo.v2 driver for connecting mongo with go. My question is: How can i auto-increment the _id field of my document so that whenever i try to perform POST operation, it should auto increment the _id field of the document ? I want to implement something similar to "FindAndModify" function but i don't see this function in go. This is what i want to try in go. Auto increment id in mongodb
type count struct {
ID string `bson:"_id"`
Seq int `bson:"seq"`
}
var doc count
func get NextSequence(name string) int{
change := mgo.Change{
Update: collection.Update(count{ID: "userid"}, bson.M{"$inc": count{Seq: 1}}),
ReturnNew: true,
}
_, err1 := collection.Find(bson.M{}).Apply(change, &doc)
return doc.Seq
}
func main(){
fmt.Println(getNextSequence("userid"))
fmt.Println(getNextSequence("userid"))
doc2 := msg{ID: getNextSequence("userid"), Name: "Sarah"}
doc3 := msg{ID: getNextSequence("userid"), Name: "Sarah2"}
}
I tried the above code, but the value of Seq does not seem to increment.It gives me 0 everytime i make a call to the function. Thanks for the help.