Querying a mongo DB collection into a struct

时间:2016-04-04 17:32:01

标签: go mgo

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 个答案:

答案 0 :(得分:1)

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.

相关问题