Search code examples
mongodbgomgo

Can not retrieve value using mgo when the key contains uppercase


One data from mongoDB is

{
    "_id" : ObjectId("5536def4e4b0644323e219a8"),
    "title" : "The Title",
    "description" : "The Description",
    "timeStamp" : "21/04/2015",
    "category" : "news",
    "url" : "http://www.example.com",
    "source" : "Evening Times",
    "mainStory" : "This is the main story."
}

In my code, the structure is

type NewsData struct {
    Title       string `bson: "title" json: "title"`
    TimeStamp   string `bson: "timeStamp" json: "timeStamp"`
    Description string `bson: "description" json: "description"`
    MainStory   string `bson: "mainStory" json:"mainStory"`
}

Then I use the following code to extract information

err = conn.Find(nil).Select(bson.M{"title": 1, "timeStamp": 1, "description": 1, "mainStory": 1}).All(&result)

However, when I print result out, the value of timeStamp and mainStory is empty. I checked the documents, it says that mgo take the key as lowercase, so when the key in mongoDB contains uppercase, it would be a problem.

How can I fix this problem?


Solution

  • There is a syntax error in the field tag. Remove the space between the ':' and the '"' in the field tag.

    TimeStamp   string `bson:"timeStamp" json:"timeStamp"`
    

    The syntax for field tags is unforgiving.

    Separate from this issue, you should probably add

    ID bson.ObjectId `bson:"_id"` 
    

    to the struct the application can access the object id.