简体   繁体   中英

How to auto-increment id field of mongodb with golang mgo driver?

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.

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)

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

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,

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM