使用mgo在MongoDB中插入数据。

huangapple go评论79阅读模式
英文:

Insert data in MongoDB using mgo

问题

我正在尝试使用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"
}
//没有大括号

谢谢。

英文:

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

得分: 0

首先,你似乎希望按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"
}
英文:

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("\n\t\"%s\":\"%v\"", slow.Endpoint, slow.Time)))
}
w.Write([]byte("\n}"))

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

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

huangapple
  • 本文由 发表于 2017年1月23日 09:17:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/41797976.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定