Reputation: 2608
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.
Upvotes: 3
Views: 7723
Reputation: 2612
Might be late but you can also use night-codes/mgo-ai package to manage your sequences.
I personally used this, I created a separate sequences
collection to store the incremented values. I also kept the _id
field and had a separate id
field for my sequence
value.
From its README.md
:
package main
import (
"github.com/night-codes/mgo-ai"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
func main() {
session, err := mgo.Dial("localhost")
if err != nil {
panic(err)
}
// connect AutoIncrement to collection "counters"
ai.Connect(session.DB("example-db").C("counters"))
// ...
// use AutoIncrement
session.DB("example-db").C("users").Insert(bson.M{
"_id": ai.Next("users"),
"login": "test",
"age": 32,
}
Upvotes: 1
Reputation: 58
Try the below one
Declare one more variable name var total_doc int'
Then do collection.Find(bson.M{}).Count(total_doc)
this will return the total number of document your have in you mongodb database.
After add doc.Seq = total_doc + 1
.This will keep on incrementing the sequence value whenever a new document gets added.
Hope this could help you
Upvotes: 1
Reputation: 5238
According to the mgo package documentation, you can use Query.Apply for that. I haven't tried it myself, but the example given there seems to already do what you want to achieve:
change := mgo.Change{
Update: bson.M{"$inc": bson.M{"n": 1}},
ReturnNew: true,
}
info, err = col.Find(M{"_id": id}).Apply(change, &doc)
fmt.Println(doc.N)
Upvotes: 4