英文:
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"
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论