retrieve a nested document with mgo

2019-07-27 12:32发布

I need to retrieve a nested document in mongoDB with mgo.
Here is my document in db:

{
    "_id" : "packing_type_0000",
    "name" : "packing",
    "category" : "logistics",
    "en" : {
            "translatedName" : "Packing and Order Prep",
    },
}

This is my golang structure:

type jobTypeWording struct {
     translatedName     string `json:"translatedName" bson:"translatedName"`
}

type jobType struct {
    ID               string         `json:"_id" bson:"_id"`
    Name             string         `json:"name" bson:"name"`
    Category         string         `json:"category" bson:"category"`
    en               jobTypeWording `json:"en" bson:"en"`
}

And my code:

result := jobType{}
sessionCopy := session.Copy()
defer sessionCopy.Close()
c := sessionCopy.DB(os.Getenv("DB_DATABASE")).C("jobTypes")
err := c.Find(bson.M{"_id": Id}).One(&result)  
fmt.Println(result.en)

My program program output:

{  }

How do I retrieve en.translatedName?

In the same program I get other nested bson from mongo and it's working with same way. I don't understand my mistake.

1条回答
放荡不羁爱自由
2楼-- · 2019-07-27 13:26

I found solution, it's because my field en began by a lower case. If i change en by En and translatedName by TranslatedName, it's work.
Here a more details answer

查看更多
登录 后发表回答