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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog