英文:
Can not retrieve value using mgo when the key contains uppercase
问题
从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
时,timeStamp
和mainStory
的值为空。我检查了文档,它说mgo将键视为小写,所以当mongoDB中的键包含大写字母时,会出现问题。
如何解决这个问题?
英文:
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?
答案1
得分: 1
字段标签中存在语法错误。在字段标签中的冒号(:)和引号(")之间删除空格。
TimeStamp string `bson:"timeStamp" json:"timeStamp"`
字段标签的语法是严格的。
除此之外,你可能应该在结构体中添加
ID bson.ObjectId `bson:"_id"`
以便应用程序可以访问对象ID。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论