globalsign / mgo

The MongoDB driver for Go
Other
1.97k stars 230 forks source link

Dot notation in structs #164

Closed simonmeusel closed 6 years ago

simonmeusel commented 6 years ago

How can I access nested fields from the mongodb response?

If I recieve the following (parsed into a map by mgo.bson and converted to json):

[{
  "outer": {
     "inner": "important"
  }
}]

And I'm trying to load it into a struct:

results := []struct {
  Test string `bson:"outer.inner"`
}{}

err := c.Pipe(pipe).All(&results)

But the field is just empty, so how do I load the fields into a struct?

domodwyer commented 6 years ago

Hi @simonmeusel

You need to use a nested struct:

type innerResult struct {
  Test string `bson:"inner"`
}

results := []struct {
  Outer innerResult `bson:"outer"`
}{}

It's best to try stack overflow for usage questions - the issues tracker is mainly for bugs / features.

Dom