doumengwei0138
doumengwei0138
2016-05-24 04:41
浏览 64

使用Go和mgo解析MongoDB结果

I am trying to parse the results of a MongoDB query from Go. 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:

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

I have been over the documentation in the following locations:

https://labix.org/mgo

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

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

I would be extemely grateful for any help that can be given. Thank You.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duannao3819
    duannao3819 2016-05-24 05:24
    已采纳

    Remove the space in the middle of tags.

    Use bson:"firstName" instead of 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,

    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.

    点赞 评论

相关推荐