我正在尝试解析来自 Go 的 MongoDB 查询的结果。由于以下原因,我有从我的数据库输出的文档:
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"
}
这是我尝试使用的 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)
}
}
当我运行此代码时,我得到以下输出:
Name: { }
Name: { }
Name: { }
当使用 res.FirstName 代替 res 时,我只是得到一个空格来代替 {}。
我已经阅读了以下位置的文档:
https://labix.org/mgo
https://godoc.org/gopkg.in/mgo.v2#Collection.Find
https://gist.github.com/border/3489566
我将非常感谢可以提供的任何帮助。谢谢。
Helenr
相关分类