将 Bson.M 转换为 map[string] 接口
Convert Bson.M to a map[string]interface
我正在尝试将我正在使用查询解码的结构转换为 map[string]interface
。
这是我的代码:
var m map[string]interface
var result []Result
type Result struct {
Id ResultId `bson:"_id"`
Filename string `bson:"filename"`
}
type ResultId struct {
Host string `bson:"host"`
}
group := bson.D{{"$group", bson.D{{"_id", bson.D{{"host","$host"}}}, {"filename", bson.D{{"$last","$filename"}}}}}}
collection := client.Database("mongodb").Collection("Meta")
cursor, err := collection.Aggregate(ctx, mongo.Pipeline{group})
if err != nil {
return c.JSON(http.StatusInternalServerError, err)
}
defer cursor.Close(ctx)
if err = cursor.All(ctx, &results); err != nil {
fmt.Printf("cursor.All() error:", err)
return c.JSON(http.StatusInternalServerError, err)
}
for _, value := range results {
m = append(m,&bson.M{value.Id.Host:value.Filename})
}
但它没有 return 地图 [string] 界面,我使用 go.mongodb.org 包作为参考。
append
仅适用于切片,(有关附加的更多信息,请参阅 effective go's section)
向地图添加元素的方法很简单:
m["key"] = value
另外请记住地图需要初始化,我在您的代码中没有看到。使用 make
或给定初始值(可以是空值)
我正在尝试将我正在使用查询解码的结构转换为 map[string]interface
。
这是我的代码:
var m map[string]interface
var result []Result
type Result struct {
Id ResultId `bson:"_id"`
Filename string `bson:"filename"`
}
type ResultId struct {
Host string `bson:"host"`
}
group := bson.D{{"$group", bson.D{{"_id", bson.D{{"host","$host"}}}, {"filename", bson.D{{"$last","$filename"}}}}}}
collection := client.Database("mongodb").Collection("Meta")
cursor, err := collection.Aggregate(ctx, mongo.Pipeline{group})
if err != nil {
return c.JSON(http.StatusInternalServerError, err)
}
defer cursor.Close(ctx)
if err = cursor.All(ctx, &results); err != nil {
fmt.Printf("cursor.All() error:", err)
return c.JSON(http.StatusInternalServerError, err)
}
for _, value := range results {
m = append(m,&bson.M{value.Id.Host:value.Filename})
}
但它没有 return 地图 [string] 界面,我使用 go.mongodb.org 包作为参考。
append
仅适用于切片,(有关附加的更多信息,请参阅 effective go's section)
向地图添加元素的方法很简单:
m["key"] = value
另外请记住地图需要初始化,我在您的代码中没有看到。使用 make
或给定初始值(可以是空值)