使用 Go 和 mgo 解析 MongoDB 个结果

Parse MongoDB results Using Go and mgo

我正在尝试解析来自 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 时,我只得到一个 space 代替 {}。

我已经阅读了以下位置的文档:

https://labix.org/mgo

https://godoc.org/gopkg.in/mgo.v2#Collection.Find

https://gist.github.com/border/3489566

如果能提供任何帮助,我将不胜感激。谢谢。

删除标签中间的 space。

使用bson:"firstName"代替bson: "firstName"

type Person struct {
    FirstName string `bson:"firstName" json:"firstName"`
    LastName string `bson:"lastName json:"lastName"`
}

来自 https://golang.org/pkg/reflect/#StructTag

的文档

By convention, tag strings are a concatenation of optionally space-separated key:"value" pairs.

所以key和value之间不应该有space。不同的键和值对可以用 space.

分隔