当密钥包含大写时,无法使用mgo检索值

时间:2015-06-30 23:51:12

标签: mongodb go mgo

来自mongoDB的一个数据是

{
    "_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."
}

在我的代码中,结构是

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"`
}

然后我使用以下代码提取信息

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

但是,当我打印result时,timeStampmainStory的值为空。我检查了文件,它说mgo把密钥作为小写,所以当mongoDB中的密钥包含大写时,这将是一个问题。

如何解决此问题?

1 个答案:

答案 0 :(得分:1)

字段标记中存在语法错误。删除':'之间的空格。而且'"'在字段标记中。

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

字段标记的语法是不可原谅的。

除了这个问题,你应该添加

ID bson.ObjectId `bson:"_id"` 

到结构,应用程序可以访问对象id。