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\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 {}.
I have been over the documentation in the following locations:
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.