将MongoDB集合查询到一个结构体中。

huangapple go评论70阅读模式
英文:

Querying a mongo DB collection into a struct

问题

定义这个结构体:

type SymbolMCAddrPort struct {
    ID        bson.ObjectId `bson:"_id,omitempty"`
    Symbol    string
    MCAddr    string
    MCPort    int
}

连接数据库并查询数据:

session, err := mgo.Dial("10.0.0.61")
if err != nil {
    panic(err)
}

defer session.Close()

csap := session.DB("FX").C("MCAddrPortPairs")

var resultsSMP bson.M
err = csap.Find(bson.M{"Symbol": "EUR/USD"}).One(&resultsSMP)
fmt.Println(resultsSMP)

如果你这样写,你会正确地看到:

map[_id:ObjectIdHex("56fc34e961fed32064e656b0") Symbol:EUR/USD MCAddr:239.0.0.222 MCPort:345]

但是如果你这样写:

resultsSMP := SymbolMCAddrPort{}
err = csap.Find(bson.M{"Symbol": "EUR/USD"}).One(&resultsSMP)

if err != nil {
    panic(err)
}

fmt.Println(resultsSMP)

你只会看到:

{ObjectIdHex("56fc34e961fed32064e656b0")   0}

我注意到ID是正确的,但是我无法获取结构体中的其他字段。

英文:

Defining this struct

type SymbolMCAddrPort struct {
	    ID        bson.ObjectId `bson:"_id,omitempty"`
        Symbol    string
        MCAddr 	  string
        MCPort 	  int
}

session, err := mgo.Dial("10.0.0.61")
if err != nil {
    panic(err)
}

defer session.Close()

csap := session.DB("FX").C("MCAddrPortPairs")

If I say

var resultsSMP bson.M
err = csap.Find(bson.M{"Symbol": "EUR/USD"}).One(&resultsSMP)
fmt.Println(resultsSMP)

I correctly see

map[_id:ObjectIdHex("56fc34e961fed32064e656b0") Symbol:EUR/USD MCAddr:239.0.0.222 MCPort:345]

But if I say

resultsSMP := SymbolMCAddrPort{}
err = csap.Find(bson.M{"Symbol": "EUR/USD"}).One(&resultsSMP)

if err != nil {
	panic(err)
}

fmt.Println(resultsSMP)

I just see

{ObjectIdHex("56fc34e961fed32064e656b0")   0}

I note that the ID is correct, but I can't get the rest of the fields in the struct?

答案1

得分: 1

使用标签来提示Unmarshal每个字段的键名是什么。

type SymbolMCAddrPort struct {
   ID        bson.ObjectId `bson:"_id,omitempty"`
   Symbol    string `bson:"Symbol"`
   MCAddr    string `bson:"MCAddr"`
   MCPort    int `bson:"MCPort"`
}

根据Unmarshal的文档,

小写的字段名被用作每个导出字段的键,但是可以使用相应的字段标签来更改此行为。

因此,默认情况下,当您使用结构体时,它期望键是字段名的小写值。当键名应该是其他内容时,必须使用字段标签来指定键名。

英文:

Use tags to hint Unmarshal what the key names for each field are.

type SymbolMCAddrPort struct {
   ID        bson.ObjectId `bson:"_id,omitempty"`
   Symbol    string `bson:"Symbol"`
   MCAddr    string `bson:"MCAddr"`
   MCPort    int `bson:"MCPort"`
}

From documentation of Unmarshal,

> The lowercased field name is used as the key for each exported field,
> but this behavior may be changed using the respective field tag.

So by default, when you are using a struct, it expects keys to be lowercased values of field names. When the key name should be anything else field tags have to be used to specify the key name.

huangapple
  • 本文由 发表于 2016年4月5日 01:32:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/36409158.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定