dongxizhe9755 2017-01-23 01:17
浏览 41
已采纳

使用mgo在MongoDB中插入数据

I'm trying to insert some data in MongoDB using mgo but the outcome is not what I wanted.

My struct

    type Slow struct {
    Endpoint string
    Time     string
    }

My insert statement

err := collection.Insert(&Slow{endpoint, e}) 
if err != nil {
    panic(err)
}

How I'm trying to print it

    var results []Slow

    err := collection.Find(nil).All(&results)
    if err != nil {
        panic(err)
    }   
    s, _ := json.MarshalIndent(results, "  ", "  ")
    w.Write(s)

My output (Marshaled JSON)

   [{
       "Endpoint": "/api/endpoint1",
       "Time": "0.8s"
    },
    {
       "Endpoint": "/api/endpoint2",
       "Time": "0.7s"
    }]

What I wanted

    {
      "/api/endpoint1":"0.8s",
      "/api/endpoint2":"0.7s"
    }
    //No brackets

Thank you.

  • 写回答

1条回答 默认 最新

  • douyong1974 2017-01-23 08:46
    关注

    First, you seem to want the results sorted by Endpoint. If you don't specify any sort order when querying, you can have no guarantee of any specific order. So query them like this:

    err := collection.Find(nil).Sort("endpoint").All(&results)
    

    Next, what you want is not the JSON representation of the results. To get the format you want, use the following loop:

    w.Write([]byte{'{'})
    for i, slow := range results {
        if i > 0 {
            w.Write([]byte{','})
        }
        w.Write([]byte(fmt.Sprintf("
    \t\"%s\":\"%v\"", slow.Endpoint, slow.Time)))
    }
    w.Write([]byte("
    }"))
    

    Output is as you expect it (try it on the Go Playground):

    {
        "/api/endpoint1":"0.8s",
        "/api/endpoint2":"0.7s"
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问各位,如何在Jetson nano主控板的Ubuntu系统中安装PyQt5
  • ¥15 MAC安装佳能LBP2900驱动的网盘提取码
  • ¥400 微信停车小程序谁懂的来
  • ¥15 ATAC测序到底用什么peak文件做Diffbind差异分析
  • ¥15 安装ubantu过程中第一个vfat 文件挂载失败
  • ¥20 GZ::CTF如何兼容一些靶机?
  • ¥15 etcd集群部署问题
  • ¥20 谁可以帮我一下问一下各位
  • ¥15 为何重叠加权后love图的SMD与svyCreateTableOne函数绘制基线表的不一致
  • ¥150 求 《小魔指》街机游戏机整合模拟软件