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

Vel*_*dan 2 go mongodb mgo

我正在与 MGO 合作(因为我没有找到比它更好的东西)。我已经玩过它并得到了一些结果,但我不明白如何获取收到文档的 _id (内部 Mongo ObjectId)?

例如:

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!
Run Code Online (Sandbox Code Playgroud)

有人可以帮我吗?我可以在哪里阅读有关它的一些信息?我在 MGO 文档中没有找到任何内容

我的文档的架构是:

{ "_id" : ObjectId("50778ce69331a280cf4bcf90"), "value" : 62 }
Run Code Online (Sandbox Code Playgroud)

谢谢!

Him*_*shu 6

  1. 将变量更改_id为大写(ID)以使其可导出。
  2. 用作bson.ObjectID其类型。
  3. 为 struct FunnyNumberId 变量添加标签。场地

需要完成以上三件事才能获取对象 Id 值。

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
}
Run Code Online (Sandbox Code Playgroud)

查看BSON包,以更好地了解在使用 mongodb 时使用 bson 标签