【问题标题】:Insert data in MongoDB using mgo使用 mgo 在 MongoDB 中插入数据
【发布时间】:2017-01-23 16:52:33
【问题描述】:

我正在尝试使用 mgo 在 MongoDB 中插入一些数据,但结果不是我想要的。

我的结构

    type Slow struct {
    Endpoint string
    Time     string
    }

我的插入语句

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

我如何尝试打印它

    var results []Slow

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

我的输出(编组 JSON)

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

我想要什么

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

谢谢。

【问题讨论】:

    标签: mongodb go mgo


    【解决方案1】:

    首先,您似乎希望结果按Endpoint 排序。如果查询时不指定任何排序顺序,则无法保证任何特定顺序。所以像这样查询它们:

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

    接下来,您想要的不是结果的 JSON 表示。要获得您想要的格式,请使用以下循环:

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

    输出如您所愿(在Go Playground 上尝试):

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

    【讨论】:

    • 感谢icza的回答,完美解决了问题。
    猜你喜欢
    • 2014-06-29
    • 2016-01-07
    • 2018-07-28
    • 2016-08-18
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    • 2021-02-13
    • 2020-01-02
    相关资源
    最近更新 更多