doujiao3998 2018-03-24 19:15
浏览 39
已采纳

如何在Gogo的MGO mongo db驱动程序中获取我的文档的ObjectId(_id)

I'm working with MGO (cause I didn't found anything better that it). I'have played with it and have got some result but I don't understand how to get the _id (internal Mongo ObjectId) of document received?

For ex:

type FunnyNumber struct {
    Value int
    _id string
}

session, err := mgo.Dial("127.0.0.1:27017")
if err != nil {
    panic(err)
}
defer session.Close()

// Optional. Switch the session to a monotonic behavior.
session.SetMode(mgo.Monotonic, true)

c := session.DB("m101").C("funnynumbers")

funnynumber := FunnyNumber{}
err = c.Find(bson.M{}).One(&funnynumber)
if err != nil {
    log.Fatal(err)
}

fmt.Println("Id one:", funnynumber._id)  // Nothing here? WHy? How to get it.
fmt.Println("Value one:", funnynumber.Value)  // 62. It's OK!

Could someone help me, please? Ot where might I read some info about it? I haven't found anything in the MGO doc

Schema of my document is:

{ "_id" : ObjectId("50778ce69331a280cf4bcf90"), "value" : 62 }

Thanks!

  • 写回答

1条回答 默认 最新

  • douqu2481 2018-03-24 19:25
    关注
    1. Change _id variable to uppercase(ID) to make it exportable.
    2. Use bson.ObjectID as its type.
    3. Add tag for struct FunnyNumber Id variable. field

    Above three things should be done to get object Id value.

    import "labix.org/v2/mgo/bson"
    
    type FunnyNumber struct {
        Value int `json:"value"`
        Id bson.ObjectId `bson:"_id,omitempty"`` // only uppercase variables can be exported
    }
    

    Take a look at package BSON for more understanding on using bson tags when working with mongodb

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料