AlwaysNull
AlwaysNull

Reputation: 348

Matching structure to mgo result

I have the following document in my local mongodb:

_id 25dd9d29-efd5-4b4e-8af0-360c49fdba31
name Reykjavik
initialDiseaseColouring blue

In my code I set up a city structure as the following:

type City struct {
    ID bson.ObjectId `bson:"_id,omitempty"`
    Name string
    InitialDiseaseColouring string
}

I'm querying it using

result := City{}
collection.Find(bson.M{"name":"Reykjavik"}).One(&result)

When I try to access the initialDiseaseColouring attribute it's not there

This is result when I print it:

{ObjectIdHex("32356464396432392d656664352d346234652d386166302d333630633439666462613331") Reykjavik }

Does anyone know why?

I was following the example on https://gist.github.com/border/3489566

Upvotes: 0

Views: 82

Answers (1)

Thundercat
Thundercat

Reputation: 120941

By default, the bson codec uses the lowercased field name as the key. Use the field tag to specify a different key:

type City struct {
    ID bson.ObjectId `bson:"_id,omitempty"`
    Name string
    InitialDiseaseColouring string `bson:"initialDiseaseColouring"`
}

The addition of the field tag changes the key from "initialdiseasecolouring" to "initialDiseaseColouring".

Upvotes: 1

Related Questions