[英]Parse MongoDB results Using Go and mgo
I am trying to parse the results of a MongoDB query from Go. 我试图从Go解析MongoDB查询的结果。 I have document(s) that output from my Database as a result of: 由于以下原因,我有从我的数据库输出的文档:
db.getCollection('People').find({})
{
"_id" : ObjectId("5730fd75113c8b08703b5974"),
"firstName" : "George",
"lastName" : "FakeLastName"
}
{
"_id" : ObjectId("5730fd75113c8b08703b5975"),
"firstName" : "John",
"lastName" : "Doe"
}
{
"_id" : ObjectId("5730fd75113c8b08703b5976"),
"firstName" : "Jane",
"lastName" : "Doe"
}
Here is the Go code that I am trying to use: 这是我尝试使用的Go代码:
package main
import (
"fmt"
"log"
"gopkg.in/mgo.v2"
)
type Person struct {
FirstName string `bson: "firstName" json: "firstName"`
LastName string `bson: "lastName json: "lastName"`
}
func main() {
session, err := mgo.Dial("10.0.0.89")
if err != nil {
panic(err)
}
defer session.Close()
// Optional. Switch the session to a monotonic behavior.
session.SetMode(mgo.Monotonic, true)
c := session.DB("PeopleDatabase").C("People")
var people []Person
err = c.Find(nil).All(&people)
if err != nil {
log.Fatal(err)
}
for _, res := range people{
fmt.Printf("Name: %v\n", res)
}
}
When I run this code I get the following Output: 当我运行此代码时,我得到以下输出:
Name: { }
Name: { }
Name: { }
When using res.FirstName in place of res I just get a space in lieu of the {}. 当使用res.FirstName代替res时,我只需要一个空格来代替{}。
I have been over the documentation in the following locations: 我已经浏览了以下位置的文档:
https://labix.org/mgo https://labix.org/mgo
https://godoc.org/gopkg.in/mgo.v2#Collection.Find https://godoc.org/gopkg.in/mgo.v2#Collection.Find
https://gist.github.com/border/3489566 https://gist.github.com/border/3489566
I would be extemely grateful for any help that can be given. 我会非常感激任何可以给予的帮助。 Thank You. 谢谢。
Remove the space in the middle of tags. 删除标签中间的空格。
Use bson:"firstName"
instead of bson: "firstName"
使用bson:"firstName"
而不是bson: "firstName"
type Person struct {
FirstName string `bson:"firstName" json:"firstName"`
LastName string `bson:"lastName json:"lastName"`
}
From documentation at https://golang.org/pkg/reflect/#StructTag , 来自https://golang.org/pkg/reflect/#StructTag上的文档,
By convention, tag strings are a concatenation of optionally space-separated key:"value" pairs. 按照惯例,标记字符串是可选的空格分隔的键:“值”对的串联。
So there should be no space between key and value. 所以键和值之间应该没有空格。 Different pairs of a key and a value could be separated by a space. 键和值的不同对可以用空格分隔。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.