2016-05-24 04:41
浏览 66


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:


    "_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 (

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

func main() {
    session, err := mgo.Dial("")
    if err != nil {
    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 {

    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:

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

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

1条回答 默认 最新

  • 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,

    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.

    打赏 评论

相关推荐 更多相似问题