如何使用golang mgo驱动程序自动增加mongodb的id字段? [英] How to auto-increment id field of mongodb with golang mgo driver?

查看:1105
本文介绍了如何使用golang mgo驱动程序自动增加mongodb的id字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对mongodb和golang很陌生。在我的一个项目中,我想连接mongo和go。我正在使用mgo.v2驱动程序将mongo与go连接。我的问题是:
如何自动递增我的文档的_id字段,以便每当我尝试执行POST操作时,它应该自动递增文档的_id字段?
我想实现类似于FindAndModify函数的功能,但是我没有看到这个功能。
这就是我想要去尝试。
在mongodb中自动增加id

 类型计数结构{
ID字符串`bson:_ id`
Seq int`bson: seq`
}

var doc count

func获取NextSequence(名称字符串)int {
change:= mgo.Change {
更新: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 ),名称:Sarah}
doc3:= msg {ID:getNextSequence(userid),Name:Sarah2}
}

我尝试了上面的代码,bu t Seq的值似乎不会增加。每当我拨打该功能时,它都会给我0。
感谢您的帮助。

解决方案

根据mgo软件包文档,您可以使用 Query.Apply 。我自己并没有尝试过,但这里给出的例子似乎已经做了你想做的事情: 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)


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)

这篇关于如何使用golang mgo驱动程序自动增加mongodb的id字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆