douzhoubing2805 2015-10-14 20:52
浏览 253

如何使用golang mgo驱动程序自动增加mongodb的id字段?

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.

  • 写回答

3条回答 默认 最新

  • dosryjij88555 2015-10-14 21:38
    关注

    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)
    
    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line