如何在 MGO mongo golang 的数据库驱动程序中获取我的文档的 ObjectId (_id)
How to get ObjectId (_id) of my document in MGO mongo db driver for golang
我正在使用 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!
有人可以帮帮我吗?或者我在哪里可以阅读有关它的一些信息?我在 MGO 文档中没有找到任何内容
我的文档架构是:
{ "_id" : ObjectId("50778ce69331a280cf4bcf90"), "value" : 62 }
谢谢!
- 将
_id
变量更改为大写 (ID) 以使其可导出。
- 使用
bson.ObjectID
作为类型。
- 为 struct
FunnyNumber
Id 变量添加标签。
字段
要获取对象 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
}
查看包 BSON 以进一步了解在使用 mongodb
时使用 bson 标签
我正在使用 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!
有人可以帮帮我吗?或者我在哪里可以阅读有关它的一些信息?我在 MGO 文档中没有找到任何内容
我的文档架构是:
{ "_id" : ObjectId("50778ce69331a280cf4bcf90"), "value" : 62 }
谢谢!
- 将
_id
变量更改为大写 (ID) 以使其可导出。 - 使用
bson.ObjectID
作为类型。 - 为 struct
FunnyNumber
Id 变量添加标签。 字段
要获取对象 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
}
查看包 BSON 以进一步了解在使用 mongodb
时使用 bson 标签