使用 mgo 在 MongoDB 中插入数据
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"
}
//No brackets
谢谢。
首先,您似乎希望结果按 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"
}
我正在尝试使用 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
谢谢。
首先,您似乎希望结果按 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"
}