doumengwei0138 2016-05-24 04:41
浏览 69
已采纳

使用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 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配